简体   繁体   中英

Get distinct list of choices from a multiple choice field's data?

I have a DataTable that contains a multi-select choice field (string). Values in the field are stored like:

Charlie
Alpha
Alpha; Charlie; Delta
Bravo; Charlie
Bravo
Alpha; Bravo; Charlie

I'm trying to get the unique list to display in a dropdown:

Alpha
Bravo
Charlie
Delta

Method to split the values and return a List<string> :

private static List<string> GetValues(string multiValueString)
{
    string[] delimiters = {"; "};
    string[] values = multiValueString.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
    return values.ToList<string>();
}

I was trying to use LINQ to get the unique values... but can't quite figure it out. I thought I could use dataTable.AsEnumerable() , do a select like .Select(r => GetValues(r.Field<string>("Brand"))) and then Union the results somehow.

But I can't quite get it working.. what am I doing wrong?

You need to use SelectMany as GetValues will return mulitple items (ie an IEnumerable ) for each row. SelectMany flattens these enumerables into a single enumerable of the resultant type:

rows.SelectMany(r => GetValues(r.Field<string>("Brand")))
    .Distinct();

The distinct removes the duplicate entries.

Use Enumerable.Distinct .

// values is IEnumerable<string> (say the return value from GetValues)
var uniqueValues = values.Distinct();

rows.SelectMany(r => GetValues(r.Field<string>("Brand"))).Distinct();

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