Search code examples
c#listmatchrecursive-queryenumerable

C# List<(string,string)> matching and replacing values


I'll try to explain this as simple as I can, it's quite a specific issue. I've been using F# for a while now and this may be causing me to get confused. What i'm trying to do is essentially (or close to) a typical recursive match statement but i'm doing this in C#.

I have a list(string s1, string s2) i'll call this list1. This consists of labels and true values.

Example: "great cause", "1"; "hyper sensitive", "2"; "increased pertinence", "3" "greater sensitive", "4";

I then have another list i'll call List2. This is a list of partial strings. For example:

"cause"; "greater"; "hyper"; "pertinence"

I want to match on the list1 (string s1,string s2) and replace the List2 string(or generate a new list) with the s2 value where s1.contains(List2).

So using the same examples as above, my end goal would be a list with the following values: "1"; "4"; "2"; "3"

Edit: I suppose in some ways this is kind of like using my List1 as a lookup table if this were a SQL query, and I want to get the actual value not the lookup code (in this case the string is the lookup code and the number is the true value)


Solution

  • You can use LINQ with Where and Select looking like this:

    var list1 = new List<(string, string)>
    {
        ("great cause", "1"), ("hyper sensitive", "2"), ("increased pertinance", "3"), ("greater sensitive", "4")   
    };
    
    var list2 = new List<string>{"cause", "greater", "hyper", "pertinance"}; // fixed typos from the post.
    var result = list2
        .Where(s => list1.Any(t => t.Item1.Contains(s)))
        .Select(s => list1.First(t => t.Item1.Contains(s)).Item2)
        .ToList();
    Console.WriteLine(string.Join(", ", result)); // prints "1, 4, 2, 3"