Help with LINQ distinct()
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 开发者_C百科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!
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.
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;
精彩评论