使用LINQ连接两个有序集合
我有两种数据类型,使用LINQ连接两个有序集合,linq,join,c#-4.0,collections,Linq,Join,C# 4.0,Collections,我有两种数据类型,Foo和Bar,它们有一个属性来确定顺序: class Foo { public int Order { get; set; } public string FooValue { get; set; } } class Bar { public int Order { get; set; } public string BarValue { get; set; } } 然后我有两个这样的集合。我想加入集合,这样结果将包含成对的Foo和Bar。
Foo
和Bar
,它们有一个属性来确定顺序:
class Foo
{
public int Order { get; set; }
public string FooValue { get; set; }
}
class Bar
{
public int Order { get; set; }
public string BarValue { get; set; }
}
然后我有两个这样的集合。我想加入集合,这样结果将包含成对的Foo
和Bar
。成对数应为条
元素数
每对都应由一个Bar
元素和最近的Foo
元素组成(FooOrder
值最大,以当前的BarOrder
值为界)
例如,对于以下集合(省略了一些语句):
结果将是:
result = {
((1, "Bar1"), (1, "Foo1")),
((6, "Bar6"), (5, "Foo5"))
};
使用LINQ和C#4.0如何实现这一点?通过使用LINQ的union(),您可以连接两个相同的元素有序集合…假设
foos
按顺序排序,您可以执行以下操作:
var fubars = from bar in bars
let bestFoo = foos.TakeWhile(foo => foo.Order <= bar.Order)
.LastOrDefault()
select new { Bar = bar, Foo = bestFoo };
var fubar=从条到条
如果允许在多个bar
对象的绑定foo
相同的情况下重复foo
,则让bestFoo=foos.TakeWhile(foo=>foo.Order:
var result = bars.Zip(foos,
(b,f) => Tuple.Create(b, foos.TakeWhile(foo => foo.Order <= b.Order).Last()));
结果将是
{
((1, "Bar1"), (1, "Foo1")),
((2, "Bar2"), (1, "Foo1")) //Foo1 again
};
foo
是否按Order
排序?是的,两个集合均按Order
var foos = new [] { new Foo(1, "Foo1"), new Foo(3, "Foo3"), new Foo(5, "Foo5")};
var bars = new [] { new Bar(1, "Bar1"), new Bar(2, "Bar2") };
{
((1, "Bar1"), (1, "Foo1")),
((2, "Bar2"), (1, "Foo1")) //Foo1 again
};