0

I've got a List properties that must contain both pivot1 and pivot2.

How can I make Contains work with BOTH values?

List<string> properties = line.Split('|').ToList();
string pivot1 = "value1";
string pivot2 = "value2";

if(properties.Contains(pivot1) && properties.Contains(pivot2))
{
// do stuff.

}
ryokan
  • 125
  • 2
  • 12
  • 4
    http://stackoverflow.com/questions/1520642/does-net-have-a-way-to-check-if-list-a-contains-all-items-in-list-b – CodeCaster Nov 11 '15 at 15:50
  • 3
    What is wrong with the code you gave? – CompuChip Nov 11 '15 at 15:52
  • What exactly are you asking? Because your `if` statement **does** already check if `properties` contains both `pivot1` and `pivot2`. Only thing is, it will throw a `NullReferenceException` as it is right now, because `properties` is declared, but not initialized. – ZiNNED Nov 11 '15 at 15:54
  • Does your code not work? It looks like it checks that properties contains both items. – Karl Gjertsen Nov 11 '15 at 15:54
  • Are you just saying you want to pass both to `Contains` instead of calling `Contains` twice? If so, that's not possible and what you have is IMO correct. – juharr Nov 11 '15 at 15:58

2 Answers2

3

Aside from writing an extension/helper method, you can use LINQ to shorten it a bit:

if (new[] { pivot1, pivot2 }.All(properties.Contains))
{

}

Although this is somewhat less readable I'd argue.


I personally like maintaining a Utility class to build up my own helpful framework to compliment .NET. I'd do something like:

 public static bool ContainsAll<T>(this IEnumerable<T> list, params T[] items)
 {
     foreach(var item in items)
     {
         if (!list.Contains(item))
             return false;
     }

     return true;
 }

then you can use:

if(properties.ContainsAll(pivot1, pivot2))
{

}
Jonesopolis
  • 25,034
  • 12
  • 68
  • 112
  • This is an elegant solution but I get the error: Severity Code Description Project File Line Error CS1106 Extension method must be defined in a non-generic static class. – ryokan Nov 11 '15 at 17:34
  • Extension methods must be in a static class. I.e. public static class Utilities... – Jonesopolis Nov 11 '15 at 17:44
0

You are not initializing properties or adding anything to it.

List<string> properties = new List<string>();

properties.Add("value1");
properties.Add("value2");

string pivot1 = "value1";
string pivot2 = "value2";

if(properties.Contains(pivot1) && properties.Contains(pivot2))
{
    // do stuff.
}
Karl Gjertsen
  • 4,690
  • 8
  • 41
  • 64