我的条形码列是字符串类型。如何按条形码列分组包含空字符串作为组和其他值只是唯一的。 我的表如下所示。
productImportList.GroupBy(f => f.BarCode);//productImportList contains list of ProductImport Class Object List
var res=productImportList.GroupBy(f => f.BarCode).Select(x=>x.First());
它的结果就像这样。
但我需要获得如下结果。
感谢。
答案 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
,空字符串和所有空格字符串都具有相同的特性。