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

  • Question

  • User-1024101449 posted

    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..?

    Tuesday, August 29, 2017 1:08 PM

Answers

  • User487807879 posted

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

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 29, 2017 1:16 PM

All replies

  • User487807879 posted

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

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, August 29, 2017 1:16 PM
  • User-1024101449 posted

    Thanks...

    Tuesday, August 29, 2017 1:18 PM
  • User303363814 posted

    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)

    Wednesday, August 30, 2017 1:40 AM