简体   繁体   English

名单 <comma-separated strings> =&gt;列表 <string> ?

[英]List<comma-separated strings> => List<string>?

Trying to come up with a LINQy way to do this, but nothing's coming to me. 试图想出一个LINQy方法来做到这一点,但没有任何事情发生在我身上。

I have a List<> of objects which include a property which is a comma-separated list of alpha codes: 我有一个List <>对象,其中包含一个以逗号分隔的alpha代码列表的属性:

lst[0].codes = "AA,BB,DD"
lst[1].codes = "AA,DD,EE"
lst[2].codes = "GG,JJ"

I'd like a list of those codes, hopefully in the form of a List of strings: 我想要一个这些代码的列表,希望以字符串列表的形式:

result = AA,BB,DD,EE,GG,JJ

Thanks for any direction. 谢谢你的任何指示。

Use SelectMany to get all split codes and use Distinct to not repeat the values. 使用SelectMany获取所有拆分代码并使用Distinct不重复这些值。 Try something like this: 尝试这样的事情:

var result = lst.SelectMany(x => x.codes.Split(",")).Distinct().ToList();

You need to use Split to split each string into multiple strings. 您需要使用Split将每个字符串拆分为多个字符串。 Then you need to use SelectMany to concatenate multiple sequences into a single sequence, and then you need to use Distinct to remove duplicates. 然后,您需要使用SelectMany将多个序列连接成一个序列,然后您需要使用Distinct来删除重复项。

var result =
    lst
    .SelectMany(x => x.codes.Split(','))
    .Distinct()
    .ToList();

如果你需要一个string作为结果:

string result = string.Join(",",lst.SelectMany(p=>p.codes.Split(",")).Distinct());

Try this: 尝试这个:

  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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM