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

时间:2016-11-16 08:53:52

标签: c# asp.net-mvc linq

我的条形码列是字符串类型。如何按条形码列分组包含空字符串作为组和其他值只是唯一的。 我的表如下所示。

table

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

它的结果就像这样。

enter image description here

但我需要获得如下结果。

enter image description here

感谢。

3 个答案:

答案 0 :(得分:2)

因此,您希望每个具有空条形码的条目最终都会显示在结果中。一个技巧可能是在分组中使空条目唯一:

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

答案 1 :(得分:1)

根据您的评论,订单无关紧要,请根据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);

请注意,上面假设没有BarCode表示其null(如果它实际上是一个空字符串,那么您可以使用.Equals(String.Empty)

答案 2 :(得分:0)

试试这个:

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

这将确保所有类型的值,null,空字符串和所有空格字符串都具有相同的特性。