Lets say I have a set of bags. Each bag contains a set of marbles. I would like to select the bags which contain a specific combination of marbles. What is the most efficient way to do this in linq?
In code:
public enum Marble { Red, Green, Blue}
public class Bag {
public string Name;
public List<Marble> contents;
}
var marbles = new[] { Marble.Red, Marble.Green };
var bags = new []
{new Bag {Name = "Foo", contents = new List<Marble> {Marble.Blue}},
new Bag {Name = "Bar", contents = new List<Marble> {Marble.Green, Marble.Red}},
new Bag {Name = "Baz", contents = new List<Marble> {Marble.Red, Marble.Green, Marble.Blue}}
};
//Output contains only bag Bar
var output = bags.Where(bag => bag.contents.All(x => marbles.Contains(x)) &&
marbles.All(x => bag.contents.Contains(x)));
Is there a better way?