簡體   English   中英

使用 LINQ 獲取不在列表中的項目

[英]Get items not in list using LINQ

有 2 個列表,我希望能夠使用 C# 獲取每個 CertID 缺少的 propId 的列表

清單1
CertID、PropID
10,1
11,3

清單2
道具ID,名稱
1、道具1
2、道具2
3、道具3

結果列表
CertId、PropId
10,2
10,3
11,1
11,2

  var rows = list1.Where(ra => !List2.AsEnumerable().Any(rb => rb.Propid == ra.propid)).tolist();

您可以使用SelectMany來展平整個列表,如以下代碼:

var result = list1
    .SelectMany(x => list2
        .Where(y => y.PropId != x.PropId)
        .Select(y => new Test { CertId = x.CertId, PropId = y.PropId }))
    .ToList();

對於測試:

1 - 課程:

public class Test
{
    public int CertId { get; set; }
    public int PropId { get; set; }
}

public class Prop
{
    public int PropId { get; set; }
    public string Name { get; set; }
}

2 - collections 的初始化:

List<Test> list1 = new List<Test>
{
    new Test{CertId=10,PropId=1},
    new Test{CertId=11,PropId=3},
};

List<Prop> list2 = new List<Prop>
{
    new Prop{PropId=1,Name="prop1"},
    new Prop{PropId=2,Name="prop2"},
    new Prop{PropId=3,Name="prop3"},
};

3 - 查詢:

var result = list1
    .SelectMany(x => list2
        .Where(y => y.PropId != x.PropId)
        .Select(y => new Test { CertId = x.CertId, PropId = y.PropId }))
    .ToList();

4 - 演示:

foreach(Test test in result)
{
    Console.WriteLine($"CertId : {test.CertId}, PropId : {test.PropId}");
}

5 - 結果:

CertId : 10, PropId : 2
CertId : 10, PropId : 3
CertId : 11, PropId : 1
CertId : 11, PropId : 2

我希望你覺得這有幫助。

我為您的問題看到的最簡單的方法是計算項目的笛卡爾積並找出差異(元組示例,我不知道您在列表中使用哪種類型)

        // Your Data
        var list1 = new List<Tuple<int, int>>
        {
            new Tuple<int, int>(10,1),
            new Tuple<int, int>(11,3),
        };

        var list2 = new List<Tuple<int, string>>
        {
            new Tuple<int, string>(1, "Prop1"),
            new Tuple<int, string>(2, "Prop2"),
            new Tuple<int, string>(3, "Prop3")
        };

        // Find the certIds and propIds, you might already have them from another source
        var certIds = list1.Select(x => x.Item1);
        var propIds = list2.Select(x => x.Item1);

        // Create cartesian product of certId x propId
        var possibilities =
        from cert in certIds
        from prop in propIds
        select new Tuple<int, int>(cert, prop);

        // Find the difference between these possibilities and what you have currently
        var missing = possibilities.Except(list1);

        // Example display
        foreach (var miss in missing)
        {
            Console.WriteLine($"{miss.Item1},{miss.Item2}");
        }
        Console.ReadKey();

您可以進行交叉連接,然后過濾不等於:

var results = (
    from l1 in list1
    from l2 in list2 
    where l1.PropId != l2.PropId
    select new { l1.CertId, l2.PropId }
).ToList();

不幸的是,LINQ 只允許在連接語句的“on”運算符中使用“equals”。 所以你不能使用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM