简体   繁体   English

在Linq中选择不同的列名称

[英]Select distinct column names in Linq

My table contains several columns and I need to select distinct rows in two specific columns using Linq. 我的表包含几列,我需要使用Linq在两个特定的列中选择不同的行。

My SQL equivalent is: 我的SQL等效项是:

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. 这将不仅检索Level1Id和Level1Name的整个行。 How can I specify the columns I want to retrieve in this linq query? 如何在此linq查询中指定要检索的列?

通过选择,您可以在匿名对象中指定列,然后在其上使用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: 在您选择的LINQ查询中指定两列,创建一个具有Level1IdLevel1Name属性的匿名对象:

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. 关键是:匿名类型使用结构比较,这就是GroupBy或任何其他答案起作用的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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