为linq查询添加select distinct

时间:2016-02-24 18:32:36

标签: linq asp.net-web-api

我的Web API控制器有一个方法,可以从数据库表中检索指定数量的描述。有不同ID的重复描述,因此有时在使用SELECT TOP时查询会返回重复项。我还添加了随机(ORDER BY NEWID)以减少获取重复的机会,但有时仍会返回重复项。我想将查询更改为SELECT DISTINCT但不确定如何在我的特定情况下执行此操作。在这里使用First()似乎很复杂。有人可以帮忙吗?我的方法如下:

public List<String> GetRandomDescriptions(string cat, string subcat, int n)
{    
    using (MyContext ctx = new MyContext())
   {
       var temp = ctx.Interactions.Where(d => (d.Category.Equals(cat) && d.Subcategory.Equals(subcat)))).OrderBy(d=>Guid.NewGuid()).Take(n).Select(d=>d.Description).ToList();
       return temp;
   }
}

这是我的班级:

 [Table("[Records]")]
    public class Interaction
    {
        [Key, Column("RECORD_ID")]
        public string DescId { get; set;}
        public string Category { get; set; }
        public string Subcategory { get; set; }
        public string Description{get; set;}
    }

2 个答案:

答案 0 :(得分:1)

你可以使用这样的东西

var result = ctx.Interactions
    .Where(d => d.Category == cat && d.Subcategory == subcat)
    .Select(d => d.Description)
    .Distinct()
    .Take(n)
    .ToList();

关键点是 - 首先应用过滤器,然后选择描述,然后使其不同,最后获取所需数量的项目。

如果您确实需要选择随机项,请在OrderBy之前插入Take

答案 1 :(得分:0)

你不需要做有趣的OrderBy构造。尝试这样的事情:

public List<String> GetRandomDescriptions(string cat, string subcat, int n)
{    
    using (MyContext ctx = new MyContext())
   {
       var temp = ctx.Interactions
                     .Where(d => d.Category.Equals(cat) && d.Subcategory.Equals(subcat)))
                     .Select(d=>d.Description)
                     .Distinct()
                     .ToList();
       return temp;
   }
}
相关问题