繁体   English   中英

如何在linq的group by中将空字符串作为一个组包含在内?

[英]How to include empty string as a group in group by in linq?

我有该字符串类型的条形码列。 如何将包括空字符串作为组和其他值的条形码列进行分组是唯一的。 我的表如下所示。

表

 productImportList.GroupBy(f => f.BarCode);//productImportList contains list of ProductImport Class Object List
var res=productImportList.GroupBy(f => f.BarCode).Select(x=>x.First());

其结果是这样的。

在此处输入图片说明

但我需要获得如下所示的结果。

在此处输入图片说明

谢谢。

因此,您希望每个带有空条形码的条目都以结果结尾。 一个技巧可能是使空条目在分组中唯一:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM