Link to home
Start Free TrialLog in
Avatar of countrymeister
countrymeister

asked on

LINQ query to select distinct values osrted in ascending order

I am trying to build a LINQ to object query to retrieve distinct set of value sorted in ascending order, where li["Location_x0020__x0020_"]. != null

Here is what I have, which does not work correctly.

 var distLocations = (from ListItem li in allLocation.AsEnumerable()
                        select new { Location = li["Location_x0020__x0020_"].ToString() }).Distinct();
Avatar of wdosanjos
wdosanjos
Flag of United States of America image

What is the problem with the LINQ query you posted?  Does it throws an exception or simply doesn't provide the results you expected?
try this:

 var distLocations = (from ListItem li in allLocation.AsEnumerable()
                        orderby Location
                        select new { Location = li["Location_x0020__x0020_"].ToString() }).Distinct();

AW
well i couldn't really understood your question, but here is what i have come up with assuming alllocation is a listbox.
I try to simulate the enviroment in my space and for the markup given below:-
<asp:ListBox id="lstValue" Width="100px" runat="server">
             <asp:ListItem>Item 1</asp:ListItem>
             <asp:ListItem>Item 2</asp:ListItem>
             <asp:ListItem>Item 3</asp:ListItem>
             <asp:ListItem Value="Value 4">Item 3</asp:ListItem>
             <asp:ListItem Text="Item 5" Value="Value 5" Selected="True"/>
             <asp:ListItem>Item 2</asp:ListItem>
         </asp:ListBox>

Open in new window


Here is the LINQ Query that will get the distinct listview items in ascending order:-
var items = lstValue.Items.Cast<ListItem>()
            .Select(item => item.Text)
            .Distinct()
            .OrderBy(s => s)
            .ToList();

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial