Help with LINQ distinct()

心不动则不痛 提交于 2021-01-27 04:54:31

问题


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!


回答1:


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.




回答2:


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;


来源:https://stackoverflow.com/questions/3970850/help-with-linq-distinct

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!