【问题标题】:Is there way to use Distinct in LINQ query syntax?有没有办法在 LINQ 查询语法中使用 Distinct?
【发布时间】:2011-04-19 18:30:07
【问题描述】:

有没有办法改写:

var tbl = ds.TABLES;
var q = from c in tbl
        select c.TABLE_TYPE;
string s = "";
foreach (var item in q.Distinct())
{
    s += "[" + item + "]";
}        
MessageBox.Show(s);

所以 Distinct() 调用在 LINQ 查询中?

【问题讨论】:

    标签: c# linq


    【解决方案1】:

    语言集成查询语法中没有Distinct() 方法语法。您可以做的最接近的方法是移动当前呼叫:

    var q = (from c in tbl
             select c.TABLE_TYPE).Distinct();
    

    【讨论】:

    • 附加信息;上面的查询在针对 sql 使用时会创建以下 sql select distinct c.TABLE_TYPE from tbl c,所以不用担心性能问题。
    【解决方案2】:

    LINQ 中的Distinct 扩展方法没有等效的查询语法。

    有关原因的更多信息,请参阅https://docs.microsoft.com/en-us/archive/blogs/charlie/linq-farm-using-distinct-and-avoiding-lambdas

    【讨论】:

    【解决方案3】:
    (from c in tbl select c.TABLE_TYPE).Distinct();
    

    【讨论】:

    • 我猜想用查询语法替换 var item in q.Distinct() 的 OP 已经意识到了这一点。一个不回答问题的帖子可以得到 14 票,真是太神奇了!
    【解决方案4】:

    如果你在 select 之后放置 distinct,VB 就有这个功能。

    【讨论】:

      【解决方案5】:

      您可以捕获 HashSet 并将 where 子句放在 select 之前:

      var hs = new HashSet<char>();
      
      from c in "abcabcd"
      where hs.Add(c)
      select c;
      

      【讨论】:

      • 聪明。唉,需要事先声明 HashSet,这会破坏查询表达式的自包含质量。
      【解决方案6】:

      在发现这个问题并意识到它不存在后为 LINQ 搜索 Distinct-function 时,我的解决方法是使用 GroupBy()。 明显的问题是 distinct-set 不包含所有数据(假设您有三个字段,但只想区分两个字段,错过了最后一个字段的值,但是,再次,t-sql 中的 DISTINCT以同样的方式工作)。

      LINQ 代码(因此是转储):

      void Main()
      {
          var gt = new GenerateThings();
          var dlist = gt.list();
          dlist.Dump();
      
          dlist.GroupBy(x => new {x.id, x.cat}).Dump();
      }
      
      public class model
      {
          public int id {get;set;}
          public int cat {get;set;}
          public int type {get;set;}
      }
      
      public class GenerateThings
      {
          public List<model>list()
          {
              var dlist = new List<model>();
              dlist.Add(createNew(1, 1, 1));
              dlist.Add(createNew(1, 1, 1));
              dlist.Add(createNew(1, 2, 1));
              dlist.Add(createNew(1, 2, 1));
              dlist.Add(createNew(1, 1, 2));
              dlist.Add(createNew(1, 1, 2));
              dlist.Add(createNew(1, 1, 2));
              return dlist;
          }
          private model createNew(int id, int cat, int type){
              return new model{
                  id = id,
                  cat = cat,
                  type = type
              };
          }
      }
      

      LINQ-dump result

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-20
        • 1970-01-01
        • 2011-05-05
        • 1970-01-01
        相关资源
        最近更新 更多