<data>
<food>
<id>1</id>
<name>asparagus</name>
<catlog>7190</catlog>
</food>
<food>
<id>2</id>
<name>almonds</name>
<catlog>7190</catlog>
</food>
<food>
<id>3</id>
<name>asparagus</name>
<catlog>7192</catlog>
</food>
<food>
<id>4</id>
<name>asparagus</name>
<catlog>7193</catlog>
</food>
</data>
i would like to get the unique catlogs, so from this list i want to extract only 7190, 7192, and 7193. i have a script that puts it into a dropdownlist by using:
DropDownList1.DataSource = dv
DropDownList1.DataBind()
but i need it to get only the unique values.
Take a look at LINQ to XML! With this you have the power to directly query a blob of xml but with less headache than using XPATH (which you could also use to do the same task).
Then you could point your datasource at the result from the LINQ query over your XML blob.
Try the following
Public Function Unique(ByVal doc As XDocument) As IEnumerable(Of String)
Return doc...<catalog>.Select(Function(x) CType(x,Integer)).Distinct()
End Function
Quick Note: The CType may seem strange at first but it does work because the XElement class defines an explicit conversion operator for many value types including Integer.
LINQ is the prefered way I think, but an another option is :
Dim newTable As DataTable = dataView.ToTable( True, "Category")
DropDownList1.DataSource = newTable
DropDownList1.DataBind()
Related
Dim distinctJoints As IEnumerable
distinctJoints = From row In spotsTable.AsEnumerable()
Group row By Key = row("FUNCJOINTCODE") Into Group
Select Key, Group
_evaluatedJointsCount = (From row In spotsTable.AsEnumerable()
Group row By Key = row("FUNCJOINTCODE") Into Group
Select Key, Group).Count()
'Process each joint
For Each currentJoint In distinctJoints
Dim currentJointKey As String = currentJoint.Key
For the above code currentJoint.Key is showing error of late binding after option strict is on.
Could you please help me out of this.
First, let me congratulate your for moving your code towards Option Strict On! It might be some work in the beginning, but it pays off in the long run since a lot of errors will be found at compile-time rather than at run-time.
That said, let's look at your problem. Here:
Dim distinctJoints As IEnumerable
you declare distinctJoints as a non-generic IEnumerable. A non-generic IEnumerable returns items of type Object when iterated over. The type Object does not contain a Key method. This is why you get a compile-time error.
Since your LINQ query returns a generic IEnumerable of an anonymous type, the solution is to use type inference instead. Activate Option Infer On (if you have not already done so) in your project properties and let the compiler infer the correct data type:
' Dim distinctJoints As IEnumerable <-- remove this
Dim distinctJoints = From row In spotsTable.AsEnumerable()
Group row By Key = row("FUNCJOINTCODE") Into Group
Select Key, Group
how to manage the result of a query that returns an integer "select count(*) from table"?
1) I've tried to bind the output of a SQL Execute Statement service to an integer variable and doesn't work. (type mistmatch)
2) i've tried to use types like 'SQLResult', SQLResultRow, SQLResultColumn as well but they dont work:
Caused by: com.lombardisoftware.core.TeamWorksException: Type ismatch the value "[Element: ]" must be and instance of type atructured IBM BPM Java Class found: org.jdom.Element
3) i've tried to bind the output to a XMLElement variable and i've got this value
< resultSet recordCount=\"1\" columnCount=\"1\">5< /columnn>< /record>< /resultSet>
so now... how can I access the recordCount attribute of this node?
anyway, I don't like so manipulate a variable of XMLType, when are the types SQLResult, SQLResultRow, SQLResultColumn used?
****** EDITED *******
even if i get a result as XMLElement.. i can't manipulate it.
methods like: tw.local.result[0].rows[0].column[0].getText() don't work (the intellisense as well)
the XMLElement as an attribute "recordCount" but i don't know how to get his value..
Anyway, the only workaround that i found is to change the query in order to return a normal set of records(not a scalar value)
select field from table instead of select count(field) from table
so i could to map the output value to a list of objects and than count its length...
ugly and dirty :-(
anyone know how manipulate the XMLElement in a script block?
Please try this.
Bind the output variable from sql execute statement as 'ANY' type.
variable name - result (ANY)
Query - select count(field) as COUNTVAL from table
tw.local.totalCount = tw.local.result[0].rows[0].indexedMap.COUNTVAL;
Use Return type as XMLElement then bind a XMLElement in output mapping.
For eg: If you are using tw.local.output as ouput mapping (of type XMLElement) then,
log.info("Count "+tw.local.output.xpath('/resultSet/record/column').item(0).getText());
This will print the count
If you want to get "recordCount" Attribute then use
tw.local.output.getAttribute("recordCount");
I have a Select query which selects the top 10 values from table
Create proc [dbo].[SP_Select_Top10]
as
select DISTINCT top (10)
Score, FBid
from
FB_Player
ORDER BY
Score DESC
What I need is to have the results of this query in xml file as.
<player>
<name> </name>
<score> </score>
</player>
I use ASP.NET to create this file how can I do that ?
Create your stored procedure like this - use the FOR XML PATH(), ROOT() syntax to have SQL Server generate a proper XML for you:
CREATE PROCEDURE dbo.procGetPlayerScore
AS BEGIN
SELECT DISTINCT TOP (10)
ID AS '#ID', -- creates an attribute on the <Player> node
Name, -- gets output as element inside <Player>
Score -- gets output as element inside <Player>
FROM
dbo.FB_Players
ORDER BY
Score DESC
FOR XML PATH('Player'), ROOT('AllPlayers')
END
In your C# code, you need something like this - connect to the database, execute the stored procedure, get back the single row, single column of that stored procedure (the XML produced):
// set up SQL Server connection and command to execute the stored procedure
using(SqlConnection conn = new SqlConnection("server=.;database=test;Integrated Security=SSPI"))
using (SqlCommand cmdGetPlayers = new SqlCommand("dbo.procGetPlayerScore", conn))
{
// define that it's a stored procedure
cmdGetPlayers.CommandType = CommandType.StoredProcedure;
// open connection, execute procedure, get resulting XML, close connection
conn.Open();
string playersXml = cmdGetPlayers.ExecuteScalar().ToString();
conn.Close();
}
As result, you'll get a XML something like this:
<AllPlayers>
<Player ID="4">
<Name>Player 4</Name>
<Score>72.1500</Score>
</Player>
<Player ID="1">
<Name>Player 1</Name>
<Score>50.5000</Score>
</Player>
......
</AllPlayers>
I would suggest looking at the native XML options of SQL Server
Link here
Also please note
<player>
<playername="" score="" />
</player>
is not valid xml, it would have to something like
<player name="" score="" />
or
<player>
<name></name>
<score></score>
</player>
depending on whether you want to be element-centric or attribute-centric, but all of these can be specified in the SQL server XML output options. Then you could just get the ASP.NET side to save the resulting query as a file.
I have created an array from a CSV of date values and now need to be able to sort them so that I can then get the latest date from the array.
I have tried:
Array.Sort()
but this doesn't sort correctly, I suppose because the array values are strings, any body got any ideas??
Thanks for any help.
CODE USED TO CREATE ARRAY
'array string exampel: "19/07/2012,23/07/2012,23/07/2012,19/07/2012,25/07/2012"
Dim ArrDates As Array = ArrDates .Split(",")
SOLUTION
Dim ArrAgentsReportCheck As Array = AgentsReportCheck.Split(",")
Dim ArrDates As New List(Of Date)
For i As Integer = 0 To ArrAgentsReportCheck.Length - 1
ArrDates.Add(ArrAgentsReportCheck(i))
Next
ArrDates.Sort()
Dim LatestDate As Date = ArrDates.Max()
ArrDates = ArrDates.OrderBy(Function(d) DateTime.ParseExact(d, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)).ToArray()
Alternately, you can use OrderByDescending() depending upon your needs.
As astander said, It is very complicated to sort a array having datetime values. Instead just convert the array to List or ArrayList and make your life easy.
For ArrayList you can use the following syntax:
List<DateTime> dates = ... // init and fill
dates.Sort();
dates.Reverse();
One way would be to convert strings to DateTime using DateTime.ParseExact
Another way just to write your own IComparer and pass to Array.Sort
I am working with ASP.net. In that in one sql query my output is 21,22,23, which is a string.
I want to remove those commas and store them as separate integer values...I want to use an array. Plese help. How to do that ?
You can convert a string separated by certain characters by using .Split(char):
string test = "21,22,23";
string[] split = test.Split(',');
This will give you an array of strings though. If you want to use them as integers you will want to convert them as well, and depending on your situation you might want to check if it's parseable or not, but you could use LINQ and do something like this:
string test = "21,22,23";
int[] values = test.Split(',').Select(value => Convert.ToInt32(value)).ToArray();
the String.Split(char[]) function should do this for you. I think in ASP.net it goes:
string values = "21,22,23";
string[] valuesArray = values.split(",");
While a normal String.Split would work, you still won't get integer values. You can try a simple LINQ query like so:
var results = from string s in yourString.Split('s')
select int.Parse(s);
You can then obviously cast it to a list or array, depending on your needs... A sample for converting it to an array directly in the LINQ query is as follows:
int[] results = (from string s in yourString.Split('s')
select int.Parse(s)).ToArray();