English 中文(简体)
Join 两部命令收集的LLINQ
原标题:Join two ordered collections with LINQ

I ve got two data category, Foo and Bar, which have a property to establish 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; }
}

然后,我收到两卷此类资料。 我也希望参加收集工作,这样,结果将包含<代码>的配对。 Foo和Bar。 奶制品的数量应为<条码> /条码>。

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).

例如,在以下汇编中(一些发言略去):

var foos = new [] { (1, "Foo1"), (2, "Foo2"), (5, "Foo5"), (7, "Foo7") };
var bars = new [] { (1, "Bar1"), (6, "Bar6") };

结果是:

result = { 
    ((1, "Bar1"), (1, "Foo1")),
    ((6, "Bar6"), (5, "Foo5"))
};

我如何用LINQ和C# 4.0来做到这一点?

最佳回答

如果您允许<条码>foo在以下情况下重复:<条码>foo对数条<条码>/条码>物体相同:

var result = bars.Zip(foos, 
        (b,f) => Tuple.Create(b, foos.TakeWhile(foo => foo.Order <= b.Order).Last()));

当然,自“条形”以来,它的效率仍然低于它的作用。 每一条“条形状”

我在<代码>foo上的重复是指对投入,如投入的投入。

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
};
问题回答

假设foosOrder分类,你可以:

var fubars = from bar in bars
             let bestFoo = foos.TakeWhile(foo => foo.Order <= bar.Order)
                               .LastOrDefault()
             select new { Bar = bar, Foo = bestFoo };

Otherwise, I suggest sorting the foos first.

你可以通过使用双轨搜索(例如,wih Array.BinarySearch)而不是像我的样本那样的线性搜索来提高这种查询的效率。

通过使用林克工会,你可以加入两部命令收集的相同内容。





相关问题
Is HashMap in Java collision safe

I am developing a parser that needs to put key value pairs in hashmap. A key can have multiple values which I can do in this way HashMap<String,ArrayList<String>> . What happens if the ...

iterating over map and array simultaneously in a for loop

I am having some trouble creating a for loop within a constructor to iterate over a map and an array at the same time. Here, it is indicated that this cannot be done with an enhanced for loop. I have ...

PLSQL Collections - how to use table of records?

I m new to PL/SQL and I m trying to use a table of records, but I don t know how to use this feature. What is the problem? DECLARE TYPE TIP IS RECORD ( F1 ...

silverlight 3 collection binding

Someone please help me understand why this binding does not work... I have a class called SelectionManager with a property called dates which is populated by a WCF service. The property is an ...

Concurrent modification whilst traversing a ruby Hash

Suppose you had this: def wipeProduct(hash, nameToDelete) hash.each do |i| key = i[0] productName = i[1].first hash.delete(key) if productName==nameToDelete end end I m not sure it ...

热门标签