简体   繁体   中英

List<comma-separated strings> => List<string>?

Trying to come up with a LINQy way to do this, but nothing's coming to me.

I have a List<> of objects which include a property which is a comma-separated list of alpha codes:

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. 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. Then you need to use SelectMany to concatenate multiple sequences into a single sequence, and then you need to use Distinct to remove duplicates.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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