帮助LINQ distinct()

twa*_*wal 6 c# linq

我有一个名为"Orders"的课程,其中包含"City"等属性.我正在尝试编写一个LINQ语句,它将从订单列表中获取所有不同的城市,并将它们作为字符串列表返回.

这就是我现在拥有的.

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

   return cities.ToList();

}
Run Code Online (Sandbox Code Playgroud)

但是,当我通过传递一个订单列表来运行它时,我似乎没有得到任何回报.该列表为空,表示它正在返回.我传递的订单都有City值.我是不是真的这么做错了?谢谢!

SLa*_*aks 14

你错误地调用了这个Distinct()方法.

将其更改为

return orders.Select(o => o.City).Distinct().ToList();
Run Code Online (Sandbox Code Playgroud)

或者,使用查询理解语法:

return (from o in orders
        select o.City
       ).Distinct().ToList();
Run Code Online (Sandbox Code Playgroud)

(注意括号)

你的代码调用DistinctCity属性本身,它是一个字符串.
String该类实现以来IEnumerable<char>,此方法返回IEnumerable<char>包含字符串中所有唯一字符的内容.
然后ToString(),您可以调用此枚举(这是一个来自System.Core.dll的编译器生成的迭代器类型),它始终返回System.Linq.Enumerable+d__81`1[System.Char].

相反,你需要调用.Distinct()IEnumerable<string>用返回的Select方法.