簡體   English   中英

使用LINQ從列表中選擇不同的數據

[英]select the distinct data from list using LINQ

我有一個包含一些屬性和列表的列表。 我想根據內部列表的屬性選擇唯一記錄,如何使用LINQ示例列表實現它

{item1 = 1, item2=2,list{a1=l1,a2=l2,a3=l5},item3 =3}
{item1 = 21, item2=21,list{a1=l11,a2=l2,a3=l3},item3 =3}
{item1 = 31, item2=22,list{a1=l12,a2=l2,a3=l3},item3 =3}
{item1 = 41, item2=23,list{a1=l1,a2=l2,a3=l3},item3 =3}

我想選擇具有屬性“ a1”的不同值的記錄。如果我發現“ a1”的重復值,那么我將比較值“ a3”!=“ l5”

預期結果:

{item1 = 21, item2=21,list{a1=l11,a2=l2,a3=l3},item3 =3}
{item1 = 31, item2=22,list{a1=l12,a2=l2,a3=l3},item3 =3}
{item1 = 41, item2=23,list{a1=l1,a2=l2,a3=l3},item3 =3}

首先,您要在內部列表a1上分組,然后在該分組中選擇a3!=“ l5”。

List<foo> col = new List<foo>();
List<string> tmp = new List<string> {"l1","l2","l5"};
col.Add(new foo {item1 = 1, item2=2,lst=tmp,item3 =3});
tmp = new List<string> {"l11","l2","l3"};
col.Add(new foo {item1 = 21, item2=21,lst=tmp,item3 =3});
tmp = new List<string> {"l12","l2","l3"};
col.Add(new foo {item1 = 31, item2=22,lst=tmp,item3 =3});
tmp = new List<string> {"l1","l2","l3"};
col.Add(new foo {item1 = 41, item2=23,lst=tmp,item3 =3});

var qry = col.GroupBy(i => i.lst[0]).Select(g => g.Where(j => j.lst[2]!="l5"));

如果有多個重復項,而您的a3不是“ l5”,那么您將得到所有重復項,因此,如果不需要,您可能需要過濾其他內容。

class Log
{
    public int DoneByEmpId { get; set; }
    public string DoneByEmpName { get; set; }

  }

public class Class1
{
    static void Range()
    {
        var array = new List<Log>() {new Log() {DoneByEmpId = 1,DoneByEmpName = "Jon"},
            new Log() { DoneByEmpId = 1, DoneByEmpName = "Jon" } ,
            new Log() { DoneByEmpId = 2, DoneByEmpName = "Max" },
            new Log() { DoneByEmpId = 2, DoneByEmpName = "Max" },
            new Log() { DoneByEmpId = 3, DoneByEmpName = "Peter" }};

        var ordered =
            array.GroupBy(x => x.DoneByEmpId).ToList().Select(x => x.FirstOrDefault()).OrderBy(x => x.DoneByEmpName);
        foreach (var item in ordered)
        {
            Console.WriteLine(item.DoneByEmpName);
        }
    }
}

結果:
喬恩
最高
彼得

暫無
暫無

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

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