James123
James123

Reputation: 11652

How to check list has all array items?

I have array of items and List of string. I need to check if list has all items of array. If yes return true or false. Will possible check with LINQ?

I tried bool flag = stringlst.Contains(new string[] { "DC", "DL", "ARP" }); it didn't work.

Note: List will have more items than the array. Array is subset of list.

Upvotes: 1

Views: 88

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

In general case when we have to count duplicates (which are ignored by Except) we can use GroupBy and check for groups:

  List<string> stringList = new List<string>() { "A", "B", "C", "B", "A", "A" };

  // "A" should appear at least 3 times, "B" at least once
  string[] arr = new string[] { "A", "B", "A", "A" };

  var actual = stringList
    .GroupBy(item => item)
    .ToDictionary(group => group.Key, group => group.Count());

  bool flag = arr
    .GroupBy(item => item)
    .All(group => actual.TryGetValue(group.Key, out var count) && count >= group.Count());

Upvotes: 0

41686d6564
41686d6564

Reputation: 19641

To make sure that the list contains all the items that are in a certain array (or any other IEnumerable), you may use the Except() method.

Example:

var stringlst = new List<string> { "Foo", "DC", "DL", "ARP", "Bar" };
var arr = new string[] { "DC", "DL", "ARP" };
bool listContainsAll = !arr.Except(stringlst).Any();    // True

Here's a generic extension method to make it easier in case it's going to be used a lot:

public static bool ContainsAll<T>(this IEnumerable<T> source, IEnumerable<T> values)
{
    return !values.Except(source).Any();
}

Usage:

bool listContainsAll = stringlst.ContainsAll(new string[] { "DC", "DL", "ARP" });

Upvotes: 3

Ondrej Tucny
Ondrej Tucny

Reputation: 27962

HashSet<T> is your friend here. Providing you can store the strings you are expecting in the list in a HashSet<T>, the IsSubsetOf method computes the required information:

var expected = new HashSet<string> { "DC", "DL", "ARP" };
bool containsAllExpected = expected.IsSubsetOf(stringlst);

It's efficient (O(n+m)) and no intermediate collection is created. In addition, if you can modify the expected set, using the ExceptWith method is even faster (O(n)):

expected.ExceptWith(stringlst);
bool containsAllExpected = expected.Count == 0;

Upvotes: 1

Related Questions