我有一个如下列表(EN可以说是默认值)
id =“1”,lang =“FR”,value =“text1FR”
id =“1”,lang =“EN”,value =“text1EN”
id =“2”,lang =“EN”,value =“text2EN”
id =“3”,lang =“FR”,value =“text3FR”
id =“3”,lang =“EN”,value =“text3EN”
有没有办法通过linq过滤此列表来获得此结果? (如果它在那里就拿FR,否则就拿EN总是在那里)
id =“1”,lang =“FR”,value =“text1FR”
id =“2”,lang =“EN”,value =“text2EN”
id =“3”,lang =“FR”,value =“text3FR”
答案 0 :(得分:2)
var result = list.GroupBy(x => x.id)
.Select(g => g.Any(x => x.lang=="FR")
? g.First(x => x.lang=="FR")
: g.First(x => x.lang=="EN"));
这更有效:
var result = list.GroupBy(x => x.id)
.Select(g => g.Where(x => x.lang == "FR")
.DefaultIfEmpty(g.First(x => x.lang == "EN"))
.First());