[英]Get distinct list of choices from a multiple choice field's data?
我有一个包含多选选择字段(字符串)的数据表。 字段中的值存储方式如下:
Charlie
Alpha
Alpha; Charlie; Delta
Bravo; Charlie
Bravo
Alpha; Bravo; Charlie
我试图获取唯一列表以显示在下拉列表中:
Alpha
Bravo
Charlie
Delta
拆分值并返回List<string>
:
private static List<string> GetValues(string multiValueString)
{
string[] delimiters = {"; "};
string[] values = multiValueString.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
return values.ToList<string>();
}
我试图使用LINQ来获取唯一值...但还不太清楚。 我以为我可以使用dataTable.AsEnumerable()
做一个选择像.Select(r => GetValues(r.Field<string>("Brand")))
然后Union
,结果不知何故。
但是我不能完全正常工作..我在做什么错?
您需要使用SelectMany
因为GetValues
将为每行返回多个项目(即IEnumerable
)。 SelectMany
这些枚举类型展平为结果类型的单个枚举类型:
rows.SelectMany(r => GetValues(r.Field<string>("Brand")))
.Distinct();
不重复项删除重复的条目。
// values is IEnumerable<string> (say the return value from GetValues)
var uniqueValues = values.Distinct();
rows.SelectMany(r => GetValues(r.Field<string>("Brand"))).Distinct();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.