[英]Group linq results by value and group null or invalid values by empty string
[英]How to include empty string as a group in group by in linq?
因此,您希望每个带有空条形码的条目都以结果结尾。 一个技巧可能是使空条目在分组中唯一:
productImportList.GroupBy(f => string.IsNullOrWhiteSpace(f.Barcode)
? Guid.NewGuid().ToString()
: f.Barcode )
.Select(x=>x.First())
结果:
Barcode title
10 abc
aaa
15 bbb
20 ccc
ddd
fff
24 ggg
48 hhh
尝试这个:
var res=productImportList.GroupBy(f => String.IsNullOrWhiteSpace(f.BarCode) ? String.Empty : f.BarCode).Select(x=>x.First());
这将确保对所有类型的值, null
,空字符串和所有空白字符串都进行相同处理。
根据您的顺序无关紧要的评论,基于BarCode()
的值创建2个查询,然后将它们连接起来。
var productImportList = ... // your query to get all data
// get all records with no BarCode
var noBC = productImportList.Where(x => x.BarCode == null);
// get the first record in each BarCode group
var hasBC = productImportList.Where(x => x.BarCode != null).GroupBy(f => f.BarCode).Select(x=>x.First());
// concatenate the queries
var result = noBC.Concat(hasBC);
请注意,以上假设no BarCode
表示其null
(如果它实际上是一个空字符串,则可以使用.Equals(String.Empty)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.