简体   繁体   中英

Using LINQ to search two lists for match and return boolean for every item

I am trying to check two lists say for example looks like this

list1 = {"br","je"}; 
list2 = {"banana", "bread", "jam", "brisket", "flakes", "jelly"};

should return

{false, true, false, true, false, true}

Using LINQ is it possible to achieve the above output. I tried something below like this

    public static IEnumerable<bool> ContainsValues(List<string> list1, List<string> list2)
{
    List<bool> res = new List<bool>();

    foreach (string item in list1)
    {
        foreach (string sub in list2)
        {
            res.Add(item.ToLower().Contains(sub.ToLower()));
        }
    }

    return res;
}

Yes, you can re-write your existing code in a single statement:

public static IEnumerable<bool> ContainsValues(List<string> list1, List<string> list2)
{
    return
        from item in list1
        from sub in list2
        select item.ToLower().Contains(sub.ToLower());
}

However, your existing code does not provide the sample results you want. To get the results you're looking for, I think you want something like this:

public static IEnumerable<bool> SecondContainsFirst(List<string> first, 
    List<string> second)
{
    return second.Select(s => first.Any(f => 
        s.IndexOf(f, StringComparison.OrdinalIgnoreCase)) > -1);
}

Here's sample usage:

private static void Main()
{
    var list1 = new List<string> {"br", "je"};
    var list2 = new List<string> {"banana", "bread", "jam", "brisket", "flakes", "jelly"};
    var result = SecondContainsFirst(list1, list2);

    Console.WriteLine($"{{{string.Join(", ", result)}}}");

    Console.Write("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}

Output

在此处输入图片说明

IEnumerable<bool> res = list2.Select(q => list1.Any(q.Contains));

Later and identical to then koryakinp's answer - took me time to make it a full fledged example - which his is not.

list2.Select(item => list1.Any(l1 => item.IndexOf(l1,StringComparison.OrdinalIgnoreCase) >= 0)); will produce the desired output:

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main(string[] args)
    {
        var list1 = new List<string> { "br", "je" };
        var list2 = new List<string> { "banana", "bread", "jam", 
                                       "brisket", "flakes", "jelly" };

        var res = list2.Select(item => 
            list1.Any(l1 => item.IndexOf(l1, StringComparison.OrdinalIgnoreCase) >= 0));


        Console.WriteLine(string.Join(",", list1));
        Console.WriteLine(string.Join(",", list2));
        Console.WriteLine(string.Join(",", res));

        Console.ReadLine();
    }
}

Output:

br,je
banana, bread, jam, brisket, flakes, jelly
False,True,False,True,False,True  // no idea why yours are lower case

Suggested edit:

To determine whether a string contains a specified substring by using something other than ordinal comparison (such as culture-sensitive comparison, or ordinal case-insensitive comparison), you can create a custom method. The following example illustrates one such approach.

Followed by an example using IndexOf() + desired StringComparison .

If only because all 3 current answers used, IMHO, troublesome string operations:

 public static void Main(string[] args)
{
    var list1 = new List<string> { "br", "je" };
    var list2 = new List<string> { "banana", "bread", "jam", "brisket", "flakes", "jelly" };

    var result = string.Join(",",ContainsValues(list1, list2));

    Console.WriteLine($"{string.Join(",",list1)}");
    Console.WriteLine($"{string.Join(",", list2)}");
    Console.WriteLine($"{result}");
    Console.Read();

    IEnumerable<bool> ContainsValues(List<string> lst1, List<string> lst2) =>
      lst2.Select(l2 => lst1.Any(l1 => l2.IndexOf(l1, StringComparison.OrdinalIgnoreCase) >= 0));
}   

`

`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM