Given these two objects:
public class Foo{
public string Result {get;set;}
public List<Bar> Bars {get;set;}
}
public class Bar{
public string Left {get;set;}
public string Right {get;set;}
}
And instances of these looking like this:
List<Foo> myFoos = new List<Foo>()
{
new Foo { Bars = new List<Bar>
{
new Bar { Left = "myLeft1", Right = "myValue1"},
new Bar { Left = "myLeft2", Right = "myValue2"}
},
Result = "TheWinningResult"},
new Foo { Bars = new List<Bar>
{
new Bar { Left = "myLeft2", Right = "myValue2"},
new Bar { Left = "myLeft3", Right = "myValue3"}
},
Result = "TheLosingResult"},
new Foo{ Bars = new List<Bar>
{
new Bar { Left = "myLeft1", Right = "myValue1"},
new Bar { Left = "myLeft2", Right = "myValue2"},
new Bar { Left = "myLeft3", Right = "myValue3"}
},
Result = "TheOtherLosingResult"},
};
List<Bar> bars = new List<Bar>()
{
new Bar{ Left = "myLeft1", Right = "myValue1" },
new Bar{ Left = "myLeft2", Right = "myValue2" }
};
I am trying to find the FirstOrDefault()
Foo
where Foo.Bars
has an exact matching bars
In this case, I am trying to return the Foo
whos Result
is "TheWinningResult"
I have tried the following:
Foo foo = myFoos.Where(t => t.Bars.All(t2 => bars.Contains(t2))).FirstOrDefault();
Foo foo = myFoos.Where(t => bars.All(r => t.Bars.Contains(r))).FirstOrDefault();
Foo foo = myFoos.FirstOrDefault(t => t.Bars.Any(r => bars.All(ru => ru.Left == r.Left && ru.Right == r.Right)));
Any idea where I am going wrong?
Update
I forgot to mention, Order of the Bars
within Foo
should not matter.