Share via


LINQ or C# - How to find exact values from string array.

Question

Tuesday, August 29, 2017 1:08 PM

I have list of array strings.

i just want to find the matching values of the string from the list of array string.

For examples,

Search StringA : SUB A

List<String> StringB = new string {"SUB A=10","SUB B=20","SUB C=90"}

I want to find and matching the values of SUB A  from StringB.

output : SUB A=10 (Matching string and value)..

How to form the query in C# Linq..?

All replies (3)

Tuesday, August 29, 2017 1:16 PM âś…Answered

Try with this:

        List<string> StringB = new List<string> { "SUB A=10", "SUB B=20", "SUB C=90" };
        string ls_SearchVal = "SUB A";
        var lobj_Result = StringB.FirstOrDefault(o => o.Contains(ls_SearchVal));

Tuesday, August 29, 2017 1:18 PM

Thanks...


Wednesday, August 30, 2017 1:40 AM

For other people who may have a similar question in the future it should be pointed out that the solution given does not work in a more general situation.  Consider if StringB is

"SUB A1=10","SUB A2=20", "SUB A=30"

The code shown will return "SUB A1=10" when the correct answer is "SUB A=30"

One way (there are many ways, of course) to get the correct answer is

var result = StringB.SingleOrDefault(s => s.Split('=')[0] == StringA);

(This is just the outline of a solution, you probably should handle leading and trailing whitespace and consider differences in case for a more robust solution)