tags:

views:

62

answers:

2

I have a class called "Orders" that has the property of "City" among others. I am trying to write a LINQ statement that will get all the distinct cities from a list of orders and return them as a list of strings.

Here is what I have now.

public List<string> GetOrderCities(List<Order> orders)
{
   IEnumerable<string> cities= from o in orders
                                select o.City.Distinct().ToString();

   return cities.ToList();

}

However, when I run this by passing it a list of orders, I don't seem to be getting anything back. The list is empty that it is returning. The orders I am passing it do all have City values. Am I just flat out doing this wrong? Thanks!

+9  A: 

You're miscalling the Distinct() method.

Change it to

return orders.Select(o => o.City).Distinct().ToList();

Or, using query comprehension syntax:

return (from o in orders
        select o.City
       ).Distinct().ToList();

(Note parentheses)

Your code calls Distinct on the City property itself, which is a string.
Since the String class implements IEnumerable<char>, this method returns an IEnumerable<char> containing all of the unique characters in the string.
You then call ToString() on this enumerable (which is a compiler-generated iterator type from System.Core.dll), which always returns System.Linq.Enumerable+d__81`1[System.Char].

Instead, you need to call .Distinct() on the IEnumerable<string> returned by the Select method.

SLaks
Oops not sure how that extra C got in there. This is just a typo on the post. The code is select s.City.Distinct().ToString();
twal
Ok I think I understand. thank you. I will make the change and give it a shot. Thanks
twal
Perfect! I thank you you!
twal
+1  A: 

You can stick with the way in which you are making the call with minor adjustments...you needed to wrap the selection area, then call Distinct() on it and then push it to a List.

List<string> cities = (from o in orders
                       select o.City).Distinct().ToList();

            return cities;
Aaron