简体   繁体   中英

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.

Based on your comment that the order does not matter, create 2 queries based on the value of BarCode() and then concatenate them.

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) )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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