【问题标题】:Get all DISTINCT items in the List with LINQ使用 LINQ 获取列表中的所有 DISTINCT 项
【发布时间】:2015-12-08 15:42:25
【问题描述】:

我对 LINQ 很陌生,如果条件满足,我有以下脚本返回表中的第一项,但是,我想获得所有不同的项,而不仅仅是第一项。我是这个平台的新手。

public LG GetLG (int WID)
{
    lock (locker) {
      return database.Table<LG> ().FirstOrDefault (x => x.id == WID);
    }
}

【问题讨论】:

标签: c#


【解决方案1】:

.Distinct() 是您要找的吗?

return database.Table<LG>.Where(x => x.id == WID).Distinct()

以下link 包含有用的材料:

例子:

List<int> ages = new List<int> { 21, 46, 46, 55, 17, 21, 55, 55 };

IEnumerable<int> distinctAges = ages.Distinct();

Console.WriteLine("Distinct ages:");

foreach (int age in distinctAges)
{
  Console.WriteLine(age);
}

此代码产生以下输出:

不同的年龄:
21
46
55
17

【讨论】:

  • 你需要重写 'Equals' 和 'GetHashCode' 方法
【解决方案2】:

在您的 LG 对象中,您需要覆盖 Equals 和 GetHashCode 方法。
完成后,您可以在 LINQ 中使用 Distinct() 函数

database.Table<LG>.Where(x => x.id == WID).Distinct()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-17
    • 1970-01-01
    • 2011-11-06
    • 2020-11-06
    • 2010-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多