简体   繁体   English

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

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

i have barcode column that string type. 我有该字符串类型的条形码列。 How to group by barcode column that include empty string as group and other value are only unique. 如何将包括空字符串作为组和其他值的条形码列进行分组是唯一的。 My Table looks like below. 我的表如下所示。

表

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

its result like something this. 其结果是这样的。

在此处输入图片说明

but i need for getting result like below. 但我需要获得如下所示的结果。

在此处输入图片说明

thanks. 谢谢。

So you want each individual entry with an empty barcode to end up in the result. 因此,您希望每个带有空条形码的条目都以结果结尾。 A trick could be to make the empty entries unique in the grouping: 一个技巧可能是使空条目在分组中唯一:

productImportList.GroupBy(f => string.IsNullOrWhiteSpace(f.Barcode)
                                  ? Guid.NewGuid().ToString() 
                                  : f.Barcode )
                 .Select(x=>x.First())

Result: 结果:

Barcode title
10  abc
    aaa
15  bbb
20  ccc
    ddd
    fff
24  ggg
48  hhh

Try this: 尝试这个:

var res=productImportList.GroupBy(f => String.IsNullOrWhiteSpace(f.BarCode) ? String.Empty : f.BarCode).Select(x=>x.First());

That will make sure that all kind of values, null , empty strings and all white space strings are treated alike. 这将确保对所有类型的值, null ,空字符串和所有空白字符串都进行相同处理。

Based on your comment that the order does not matter, create 2 queries based on the value of BarCode() and then concatenate them. 根据您的顺序无关紧要的评论,基于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);

Note the above assumes the no BarCode means its null (if its actually an empty string, then you can use .Equals(String.Empty) ) 请注意,以上假设no BarCode表示其null (如果它实际上是一个空字符串,则可以使用.Equals(String.Empty)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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