【发布时间】:2021-09-06 07:46:31
【问题描述】:
我有一个要按属性A 分组的列表。然后选择GroupBy 键为null 或'' 的该组的所有元素,然后我想返回这些组的所有元素。否则,对于组键,返回该组的第一个元素。我想出了以下内容以及我对代码的期望。任何帮助将不胜感激。
示例代码:
public class ABC
{
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
}
var list = new List<ABC>()
{
new ABC() { A = "a", B = "b", C = "c" },
new ABC() { A = "a", B = "b", C = "c" },
new ABC() { A = null, B = "b", C = "c" },
new ABC() { A = null, B = "b", C = "c" },
new ABC() { A = "", B = "b", C = "c" },
new ABC() { A = "", B = "b", C = "c" },
};
var result = list.GroupBy(x => x.A)
.Select(x =>
{
if (!string.IsNullOrEmpty(x.Key))
return x.First();
else
return x;
})
.ToList();
我的期望:
我希望从结果中看到5 的总数
{ A = "a", B = "b", C = "c" } count 1 (1 removed)
{ A = null, B = "b", C = "c" } count 2 (none removed)
{ A = "", B = "b", C = "c" } count 2 (none removed)
【问题讨论】:
-
在您的
Select中,您可以将其修改为返回列表(其中某些列表仅包含一项),例如:var result = list.GroupBy(x => x.A).Select(x => string.IsNullOrEmpty(x.Key) ? x.ToList() : new List<ABC> { x.First() }).ToList();
标签: c# .net linq asp.net-web-api .net-core