Linq select Distinct by 两个属性

Kye*_*ica 3 c# linq linq-to-entities distinct

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

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

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

就像是

let jobRank = JobProvider.Rank
...where min(rank)
Run Code Online (Sandbox Code Playgroud)

Ser*_*rvy 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));
Run Code Online (Sandbox Code Playgroud)