3

我有一个相当复杂的 LINQ 查询,它连接了几个表,并选择了一个新的匿名类型,即三个 IEnumerable's {Users, JobProviders, Jobs}。它返回一个 IQueryable 以维持延迟执行,从而消除了 DistintBy这个问题

其中一列是排名,我需要确保只有每个职位的排名最低的记录(另一列,许多职位将被选中)被选中。Distinct 不起作用,因为排名显然会使行唯一。

我认为 group 子句可能对此有所帮助,但它将返回类型更改为 IGrouping。我不完全理解小组是如何运作的,所以我可能是错的,但它看起来不起作用。有没有办法说每个工作只取最低的等级?

就像是

let jobRank = JobProvider.Rank
...where min(rank)
4

2 回答 2

5

您可以使用分组,尽管它让我畏缩使用 groupBy 来做一个独特的。您只需调用即可FirstIGrouping组中取出一个项目,这实际上是一个不同的项目。它看起来像这样:

var distinctItems = data.GroupBy(item => new{
  //include all of the properties that you want to 
  //affect the distinct-ness of the query
  item.Property1
  item.Property2
  item.Property3
})
.Select(group => group.Key);
//if it's important that you have the low rank use the one below.
// if you don't care use the line above
//.Select(group => group.Min(item => item.Rank));
于 2012-04-13T20:36:45.283 回答
2

这里很好的解决方案:

LINQ 在特定属性上的 Distinct()

你需要的是一个有效的“distinct-by”。我不相信它是 LINQ 的一部分,尽管它很容易编写:

What you need is a "distinct-by" effectively. I don't believe it's part of LINQ as it stands, although it's fairly easy to write:

public static IEnumerable<TSource> DistinctBy<TSource, TKey>
    (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
    HashSet<TKey> seenKeys = new HashSet<TKey>();
    foreach (TSource element in source)
    {
        if (seenKeys.Add(keySelector(element)))
        {
            yield return element;
        }
    }
}
于 2013-05-15T19:40:44.277 回答