简体   繁体   English

使用LINQ从列表中选择不同的数据

[英]select the distinct data from list using LINQ

I have a list which contains some properties and list. 我有一个包含一些属性和列表的列表。 I want to select the unique records based on the property of inner list how can i achieve it using LINQ Example List 我想根据内部列表的属性选择唯一记录,如何使用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}

I want to select the record which has distinct value of property "a1".If I found duplicate value of "a1" then i will compare value "a3" != "l5" 我想选择具有属性“ a1”的不同值的记录。如果我发现“ a1”的重复值,那么我将比较值“ a3”!=“ l5”

Expected Result: 预期结果:

{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}

First you want to GroupBy on your inner list a1 and then select within that grouping for a3!="l5". 首先,您要在内部列表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"));

If there are multiple duplicates where your a3 is not "l5" you will get all of them so you may need to filter on something else if this is not desired. 如果有多个重复项,而您的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);
        }
    }
}

Result : 结果:
Jon 乔恩
Max 最高
Peter 彼得

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM