Selecting distinct objects from collection of objects using lambda expressions

吃可爱长大的小学妹 提交于 2019-12-08 10:34:07

问题


We have a project using Fluent NHibernate. There is an object called BluePart with a property of Oem of type Oem.

public class BluePart : DomainEntity
{
    ...
    public virtual Oem Oem { get; set; }
}

The Oem object has several properties including OemCode and OemDescription.

public class Oem : DomainEntity
{
    ...
    public virtual string OemCode { get; set; }
    public virtual string OemDescription { get; set; }
}

I am trying to build a linq query using lambda expressions that will get all distinct Oems from a list of BlueParts (2.7million records). Ideally it should produce the following sql (which runs in <1sec):

select distinct o.OemCode, o.OemDescription 
From BluePart b inner join Oem o on o.OemId = b.Oem_id

Below is the query I built which returns all Oems, regardless of distinctness.

var oem = repository.Query<BluePart>().Select(x => new Oem { OemCode =
x.Oem.OemCode, OemDescription = x.Oem.OemDescription}).ToList();

I thought this query would be easy to build but it's not turning out to be that way. When running a GroupBy (.GroupBy(z => z.OemCode)), I keep getting an error saying the property I try to GroupBy is not a property of Bluepart (which it shouldn't be because I'm grouping on a property of Oem)


回答1:


How about:

var oem = repository.Query<BluePart>()
                    .Select(x => new { OemCode = x.Oem.OemCode, 
                                       OemDescription = x.Oem.OemDescription})
                    .Distinct()
                    .ToList();

This will only get you the distinct code/description pairs, but it looks like that's all you're interested in.

Alternatively, using grouping:

var oem = repository.Query<BluePart>()
                    .GroupBy(x => new { OemCode = x.Oem.OemCode, 
                                        OemDescription = x.Oem.OemDescription})
                    .ToList();

This will get you all the BluePart entities grouped by OEM code/description.



来源:https://stackoverflow.com/questions/3344133/selecting-distinct-objects-from-collection-of-objects-using-lambda-expressions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!