[英]Get distinct value from comma seperated array using LINQ
Supposed I have a string array like this 假设我有一个像这样的字符串数组
{ "A“, ”B", "A,B,D", "C" }
Is it possible that I write a single LinQ to get the distinct values {"A","B","C","D"} into a List? 我是否可以编写单个LinQ来将不同的值{“ A”,“ B”,“ C”,“ D”}放入列表中?
lists.SelectMany(l => l.Split(',')).Distinct().ToList();
var distinctValues = myList.SelectMany(x => x.Split(',')).Distinct().ToList();
This will split each string, and then flatten them into a single list, and get the distinct elements. 这将拆分每个字符串,然后将它们展平为一个列表,并获得不同的元素。
If you want to get the elements in alpha order, then you can tack on a .OrderBy(x => x)
right before .ToList()
. 如果
.OrderBy(x => x)
字母顺序获取元素,则可以在.OrderBy(x => x)
之前.ToList()
.OrderBy(x => x)
.ToList()
。
Fyi in linq query syntax its the same as the answers above LINQ中的Fyi查询语法与上面的答案相同
List s = new List() { "A","B","A,B,D","C"}; List s = new List(){“ A”,“ B”,“ A,B,D”,“ C”};
var result = (from x in s from y in x.Split(',') select y).Distinct().ToList(); var result =(从x中的x从x中的y从x.Split(',')选择y).Distinct()。ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.