使用Lambda表达式从对象集合中选择不同的对象 [英] Selecting distinct objects from collection of objects using lambda expressions

查看:251
本文介绍了使用Lambda表达式从对象集合中选择不同的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个使用Fluent NHibernate的项目.有一个名为BluePart的对象,该对象的Oem类型为Oem.

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; }
}

Oem对象具有多个属性,包括OemCode和OemDescription.

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; }
}

我正在尝试使用lambda表达式构建linq查询,该查询将从BlueParts列表(270万条记录)中获取所有不同的Oem.理想情况下,它应产生以下sql(在< 1sec内运行):

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

下面是我构建的查询,该查询将返回所有Oem,无论是否有区别.

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();

我认为此查询将易于构建,但事实并非如此.运行GroupBy(.GroupBy(z => z.OemCode))时,我不断收到错误消息,说我尝试GroupBy的属性不是Bluepart的属性(这不应该是因为我正在对属性进行分组Oem)

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)

推荐答案

怎么样:

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.

或者,使用分组:

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

这将为您提供按OEM代码/说明分组的所有BluePart实体.

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

这篇关于使用Lambda表达式从对象集合中选择不同的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆