2

I have a string array:

string[] initValue =
{"A=Test11,B=Test12,B=TestA,C=Test14,D=Test15",
 "A=Test21,B=Test22,B=TestA,C=Test24,D=Test25",
 "A=Test31,B=Test32,B=TestA,C=Test34,D=Test35"};

And I need the distinct values that start with "B=" and are not "B=TestA", example:

string[] resultValue =
{"Test12",
 "Test22",
 "Test32"};

How can I use Linq to get this result?

1
  • 1
    You have no strings in that array that starts with B= . A comma doesn't start a new string Commented Mar 9, 2016 at 19:03

3 Answers 3

3
string[] result = initValue.Select(v => v.Split(','))
    .SelectMany(v => v)
    .Select(v => v.Split('='))
    .Where(v => v[0] == "B" && v[1] != "TestA")
    .Select(v => v[1]).Distinct().ToArray();

First, you need to get the partial strings.
Then You reduce the resulting collections to one.
Then split the individual strings by "=" and select only those that have "B" as first value and not "TestA" as second.
Then select the second value and call Distinct, which removes duplicate values.

Sign up to request clarification or add additional context in comments.

Comments

0

Domysee's answer is fine. But one can always throw a Regular Expression to the mix for fun.

 var re = new Regex(@"B=(?<test>Test\d+)", RegexOptions.Compiled);
 string[] resultValue = re.Matches( String.Join(",", initValue))
               .OfType<Match>()
               .Select(m => m.Groups["test"].Value)
               .ToArray();

Comments

0

Here is another way to get your expected result:

         var resultValue = initValue
            .SelectMany(s => s.Split(','))
            .Where(x => x.StartsWith("B"))
            .Where(s => s != "B=TestA")
            .Select(a => a.Replace("B=", "")).ToList(); //or .ToArray(); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.