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