LINQ to SQL Select Distinct by Multiple Columns an

2020-02-14 04:35发布

问题:

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?

回答1:

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

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