LINQ to SQL Select Distinct by Multiple Columns and return entire entity

五迷三道 提交于 2019-12-18 08:27:28

问题


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


来源:https://stackoverflow.com/questions/7364354/linq-to-sql-select-distinct-by-multiple-columns-and-return-entire-entity

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