![](/img/trans.png)
[英]How to get all the rows of a table, where a column's value occurs more than once in LINQ to Entities?
[英]How to get a dictionary with Linq where keys are met more than once?
假設一個對象如:
class A {
string Country;
string Region;
}
和IEnumerable<A>
如:
"Denmark", "Arhus"
"Denmark", "Bornholm"
"Denmark", "Frederiksborg"
"Denmark", "Fyn"
"Denmark", "Copenhagen"
"Denmark", "Nordjylland"
"France", "Alsace"
"France", "Aquitaine"
"France", "Auvergne"
"France", "Basse-Normandie"
"France", "Bourgogne"
"France", "Bretagne"
"France", "Centre"
"France", "Champagne-Ardenne"
"France", "Corse"
etc...
如何使用Linq獲取IDictionary<string, IEnumerable<string>> res
,其中res['Country']
將返回對應區域的IEnumerable<string>
?
ToLookup
應該給您您想要的。
var lookup = data.ToLookup(a => a.Country, a=> a.Region);
從技術上講,它是不可變的,因此不會實現IDictionary
。 如果必須實現該接口,則需要將查找轉換為字典:
var dictionary = lookup.ToDictionary(group => group.Key,
group => group.AsEnumerable());
IDictionary<string, IEnumerable<string>> dictionary =
list.GroupBy(r => r.Country)
.ToDictionary(grp => grp.Key, grp => grp.Select(t => t.Region));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.