简体   繁体   中英

Select distinct column names in Linq

My table contains several columns and I need to select distinct rows in two specific columns using Linq.

My SQL equivalent is:

Select distinct Level1Id, Level1Name
from levels

What I currently do is:

db.levels.GroupBy(c=> c.Level1Id).Select(s => s.First())

This will retrieve the whole row not only Level1Id and Level1Name. How can I specify the columns I want to retrieve in this linq query?

通过选择,您可以在匿名对象中指定列,然后在其上使用Distinct:

  db.levels.Select(l => new{ l.Level1Id, l.Level1Name }).Distinct();

尝试

db.levels.Select(c => new {c.Level1Id, c.Level1Name}).Distinct();

Specify the two columns in your LINQ query select, create an anonymous object with Level1Id and Level1Name properties:

var query = (from v in db.levels
            select new { Level1Id = v.Level1Id, Level1Name = v.Level1Name }).Distinct();

and use each item like this:

foreach (var r in query){
  int valId = r.LevelId;
  int level = r.Level1Name;
  //do something
}

You are so close, one more step:

var result = db.levels.GroupBy(c=> new { c.Level1Id, c.Level1Name })
               .Select(s => s.First())

The key thing is: Anonymous type uses structural comparison, that's why GroupBy or any other answer do work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM