优化两个列表<T>对象、组和计数的 LINQ 连接

问题描述 投票:0回答:3

我有两个

List<T>
物体。我想要计算两个列表之间有多少项匹配。现在,当我遇到匹配项时,我可以用计数器循环......但这有点蹩脚。

然而,这扩展了我的 LINQ 知识。我相信我想做的是加入、辨别(在哪里)、分组和投影计数。我通过阅读类似的 SO 问题和 LINQ 文档来采用这种方法。

但是,如果这确实有缺陷,那么它不一定是这样的。我只想要匹配元素的数量。

所以我的“主”对象是:

public class Master
{
    public StringModel OldText { get; private set; }
    public StringModel NewText { get; private set; }

    public Master()
    {
        OldText = new StringModel();
        NewText = new StringModel();
    }
}

StringModel 是:

public class StringModel
{
    public List<strPiece> Lines { get; private set; }

    public StringModel()
    {
        Lines = new List<strPiece>();
    }
}

到目前为止我的 LINQ 是:

var unchangedJoin = from oldLine in Master.OldText.Lines
                    join newLine in Master.NewText.Lines
                    on oldLine.Type equals newLine.Type
                    where oldLine.Type == "ABC"
                    group oldLine by --as you can see I kinda break down here.

我怎样才能完成这个?

c# c#-4.0 linq-to-objects
3个回答
2
投票

听起来 intersect

很好用
var infoQuery =
    (from cust in db.Customers
    select cust.Country)
    .Intersect
        (from emp in db.Employees
        select emp.Country)
;

1
投票

只需执行

GroupJoin
而不是
Join

var unchangedJoin = from oldLine in Master.OldText.Lines
                    join newLine in Master.NewText.Lines
                    on oldLine.Type equals newLine.Type
                    into newMatches
                    where oldLine.Type == "ABC"
                    select oldLine;

var matches = unchangedJoin.Count();

0
投票

我也推荐

Intersect
。如果你这样做,使用流畅的语法会更有意义。

int matches = Master.OldText.Lines
    .Where(line => line.Type == "ABC")
    .Intersect(Master.NewText.Lines)
    .Count();
© www.soinside.com 2019 - 2024. All rights reserved.