LINQ to SQL选择不同的列并返回整个实体

时间:2022-07-15 04:27:56

I am working with a third party database and need to select a distinct set of data for the specific market that I am looking into. The data is the same for each market, so it is redundant to pull it all in, and I don't want to hardcode any logic around it as we are working with the vendor to fix the issue, but we need a fix that will work with the vendors fix as well as the way the database is currently as it could be some time before thier fix goes live.

我正在使用第三方数据库,需要为我正在调查的特定市场选择一组不同的数据。每个市场的数据都是一样的,所以把它都是多余的,我不想它周围硬编码任何逻辑,我们正在与供应商解决这个问题,但是我们需要一个修复,将与供应商修复以及数据库目前的方式可能是一段时间他们修复上线。

I do not want to group by anything as I want to get the data at the lowest level, but I don't want any redundant data. My current query looks similar to this...

我不希望对任何东西进行分组,因为我希望得到最低级别的数据,但我不希望有任何冗余数据。我当前的查询与此类似……

determinantData = (from x in dbContext.Datas
                   where x.Bar.Name.Equals(barName) &&
                         x.Something.Name.Equals(someName) &&
                         FooIds.Contains(x.Foo.Id) &&
                         x.Date >= startDate && 
                         x.Date <= endDate
                   select x).Distinct();

This does not do what I expect. I would like to select the distinct records by three properties, say Foo, Bar, and Something but return the entire object. How can I do this using LINQ?

这并不是我所期望的。我想通过三个属性来选择不同的记录,比如Foo Bar等等但是返回整个对象。我怎么用LINQ来做这个?

1 个解决方案

#1


8  

You could use group by with the properties that you want to be distinct, then select the first item of each group:

你可以使用group by和你想要区分的属性,然后选择每个组的第一项:

determinantData = (from x in dbContext.Datas
                   where x.Bar.Name.Equals(barName) &&
                         x.Something.Name.Equals(someName) &&
                         FooIds.Contains(x.Foo.Id) &&
                         x.Date >= startDate && 
                         x.Date <= endDate
                   group x by new { x.Foo, x.Bar, x.Something } into market 
                   select market).Select( g=> g.First()); 

#1


8  

You could use group by with the properties that you want to be distinct, then select the first item of each group:

你可以使用group by和你想要区分的属性,然后选择每个组的第一项:

determinantData = (from x in dbContext.Datas
                   where x.Bar.Name.Equals(barName) &&
                         x.Something.Name.Equals(someName) &&
                         FooIds.Contains(x.Foo.Id) &&
                         x.Date >= startDate && 
                         x.Date <= endDate
                   group x by new { x.Foo, x.Bar, x.Something } into market 
                   select market).Select( g=> g.First());