我试图用 LINQ 的方式来处理这个问题,但却想不出什么好的方法。
我有一个对象列表 List<>,其中包括一个属性,该属性是逗号分隔的字母代码列表:
lst[0].codes = "AA,BB,DD"
lst[1].codes = "AA,DD,EE"
lst[2].codes = "GG,JJ"
我希望获得那些代码的清单,希望是字符串列表的形式:
result = AA,BB,DD,EE,GG,JJ
感谢任何指引。
使用SelectMany
获取所有的分割代码,然后使用Distinct
来避免重复值。
var result = lst.SelectMany(x => x.codes.Split(",")).Distinct().ToList();
List<>
,但你也可以使用一个集合或其他东西,它不能有重复项,例如 var result = new SortedSet<string>(lst.SelectMany(x => x.codes.Split(",")));
。 - Jeppe Stig Nielsen.Distinct()
?用户是否要求它是唯一的?在第二个lst[1].codes
索引中,您不会删除AA
吗? - Mark BuffaloSplit
函数将每个字符串拆分成多个字符串。接着,你需要使用 SelectMany
函数将多个序列连接成一个序列,然后使用 Distinct
函数去重。var result =
lst
.SelectMany(x => x.codes.Split(','))
.Distinct()
.ToList();
string result = string.Join(",",lst.SelectMany(p=>p.codes.Split(",")).Distinct());
试试这个:
List<string> list = new List<string>();
char[] sep = new char[1];
sep[0] = ',';
foreach (string item in lst)
{
list.AddRange(item.Split(sep));
}
list = list.Distinct().ToList();
lst.SelectMany(x => x.Split(',')).Distinct().ToList()
,但需要更好的 CSV 解析... - Adriano Repetti