I’ve got two data types, Foo and Bar, that have a property to determine order:
class Foo
{
public int Order { get; set; }
public string FooValue { get; set; }
}
class Bar
{
public int Order { get; set; }
public string BarValue { get; set; }
}
Then I’ve got two collections of these types. I’d like to join the collections, so that the result will be contain pairs of Foo and Bar. The number of pairs should be the number of Bar elements.
Each pair should consist of a Bar element and the most “recent” Foo element (with largest Foo Order value, bounded by the current Bar Order value).
For example, for the following collections (some statements omitted):
var foos = new [] { (1, "Foo1"), (2, "Foo2"), (5, "Foo5"), (7, "Foo7") };
var bars = new [] { (1, "Bar1"), (6, "Bar6") };
The result would be:
result = {
((1, "Bar1"), (1, "Foo1")),
((6, "Bar6"), (5, "Foo5"))
};
How can I achieve this with LINQ and C# 4.0?
If you allow
foorepetitions in cases where the boundfoois the same for severalbarobjects:Of course it’s still less efficient than iterating, since
TakeWhilewill be called for eachbarsobject (starting from the beginning each time)What I mean by
foorepetitions is that for an input such asThe result would be