3

Im looking for a quick way to call IList.Contains with a string array argument

Is there a way to do this:

val[] = {"first", "second"}

var temp = from i in items
           where i.list.Contains(val)
           select i;
Mikkel Nielsen
  • 792
  • 2
  • 13
  • 36

5 Answers5

6

If you want to check if i.list contains either "first" or "second":

var val = new [] { "first", "second" };
var temp = from i in items
           where val.Any (i.list.Contains)
           select i;

If you want to check if i.list contains both "first" or "second":

var val = new [] { "first", "second" };
var temp = from i in items
           where val.All (i.list.Contains)
           select i;

However if performance is crucial (think called in a loop for hundreds of items), it would be more appropriate to use HashSet intersection as advised by Hermit.

Community
  • 1
  • 1
Dan Abramov
  • 264,556
  • 84
  • 409
  • 511
5
var temp = from i in items
           where i.list.Any(x => val.Contains(x)) 
           select i;

use All if all list items should be in values

Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459
3

I am really bad at LINQ so I am not going to address that.

First doing a Contains on a list isn't the fastest thing. Doing a LINQ on list isn't doing to make it any faster. What you need to do is have a HashSet and then do a Contains. if you have two lists, i'd say create two HashSets and Intersect them.

http://msdn.microsoft.com/en-us/library/vstudio/bb918911(v=vs.90).aspx

Hermit Dave
  • 3,036
  • 1
  • 13
  • 13
1

Not sure what you mean by 'contains', if you want all of the Items that match, @lazyberezovsky's answer should be correct.

However, if you want to overrride IList.Contains to support an array (or Enumerable) you can do this:

    /// <summary>
    /// Return true if <paramref name="allItems"/>
    /// contains one or more <paramref name="candidates"/>
    /// </summary>
    public static bool Contains<T>(IList<T> allItems, IEnumerable<T> candidates)
    {
        if (null == allItems)
            return false;

        if (null == candidates)
            return false;

        return allItems.Any(i => candidates.Contains(i));
    }
Philip Pittle
  • 11,821
  • 8
  • 59
  • 123
1

Here's an extension method to get whether any of the items in the array exist in the list. This one returns a bool like IList.Contains.

public static class IListExtensions
{
    public static bool ContainsAny<T>(this IList<T> list, IEnumerable<T> enumerable)
    {
        foreach (var item in enumerable)
        {
            if (list.Contains(item))
                return true;
        }
        return false;
    }
}

Usage:

IList<int> a = // ...
string[] b = // ...

a.ContainsAny(b);
Daniel Imms
  • 47,944
  • 19
  • 150
  • 166