1

Given the situation I got a string array from a file containing IDs.
Which may be separated by various characters, " " : ; etc.
I would like to obtain every string in one new list/array, using LinQ, that contained any of the given separators.
I am currently doing this in a rather inconvenient way

string[] separator = { " ", ",", ";", ".", ":", "/" };
string[] arr = { };
listExceptions = someSource;
List<string> entrysWithSeparator=
(from s in listExceptions where (ContainsAny(s,separator) == true) select s).ToList(); 
//ContainsAny returns a bool, if any of the separators was found in the string
List<string> tmpExceptions = listExceptions.ToList();

foreach (string s in entrysWithSeparator)
{                
    arr = s.Split(separator, StringSplitOptions.RemoveEmptyEntries);
    tmpExceptions.AddRange(arr.ToList());
}
listExceptions = new string[listExceptions.Count()-1];
listExceptions = tmpExceptions.Distinct().ToArray();
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
joachim
  • 652
  • 2
  • 7
  • 23
  • Why are you creating an array in the penultimate line, only to overwrite the value of the variable in the last line? I'm finding it hard to follow what you're trying to achieve - a concrete example would be useful. – Jon Skeet Feb 27 '15 at 11:30
  • How about showing the possible input data vs. what is expected – James Simpson Feb 27 '15 at 11:31
  • @JonSkeet I assume you are refering to the last two line. I had some problems not overwriting the existing array with a new one where there were some artifacts left, I didnt had any clue how to properly solve that without creating a fresh array – joachim Feb 27 '15 at 11:56

2 Answers2

1

You should be able to combine the query and the loop by using SelectMany:

listExceptions = listExceptions
    .Where(s => ContainsAny(s,separator))
    .SelectMany(s => s.Split(separator, StringSplitOptions.RemoveEmptyEntries))
    .ToArray();

I assume that you are using ContainsAny method similar to this one in your query.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0
var result = list.SelectMany(s => 
                s.Split(separator, StringSplitOptions.RemoveEmptyEntries))
             .Distinct();

There is no need for ContainsAny since Split() on a string containing no seperators also returns the string itself.

Stijn Van Antwerpen
  • 1,840
  • 17
  • 42