【问题标题】:select the distinct data from list using LINQ使用 LINQ 从列表中选择不同的数据
【发布时间】:2017-01-02 15:19:41
【问题描述】:

我有一个包含一些属性和列表的列表。我想根据内部列表的属性选择唯一记录如何使用 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}

【问题讨论】:

  • 你能提供你的类的结构吗?我不确定你是如何构建它们的(对我来说就像字典)
  • 下面的Leppie是类似的结构

标签: c# linq


【解决方案1】:

首先您要在内部列表 a1 上进行 GroupBy,然后在该分组中选择 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”有多个重复项,您将获得所有重复项,因此如果不需要,您可能需要过滤其他内容。

【讨论】:

  • 嗨,吉姆,感谢您的尝试,但在您的情况下,您正在考虑字符串列表,而在我的情况下,它也是对象列表。所以 i.lst[index] 可能是不可能的。
  • 在这种情况下,您可以只访问子对象的元素。
【解决方案2】:
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);
        }
    }
}

结果:
乔恩
马克斯
彼得

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多