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 开发者_JAVA技巧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 (i.e. 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();
精彩评论