简体   繁体   English

使用LINQ选择列中的所有不同值

[英]Select All distinct values in a column using LINQ

I created a Web Api in VS 2012. I am trying to get all the value from one column "Category", that is all the unique value, I don't want the list to be returned with duplicates. 我在VS 2012中创建了一个Web Api。我试图从“类别”列中获取所有值,即所有唯一值,我不希望该列表与重复项一起返回。

I used this code to get products in a particular category. 我使用此代码来获取特定类别的产品。 How do I get a full list of categories (All the unique values in the Category Column)? 如何获得类别的完整列表(“类别”列中的所有唯一值)?

public IEnumerable<Product> GetProductsByCategory(string category)
    {
        return repository.GetAllProducts().Where(
            p => string.Equals(p.Category, category, StringComparison.OrdinalIgnoreCase));
    }

To have unique Categories: 具有独特的类别:

var uniqueCategories =  repository.GetAllProducts()
                                  .Select(p=>p.Category)
                                  .Distinct();
var uniq = allvalues.GroupBy(x => x.Id).Select(y=>y.First()).Distinct();

简单容易

I have to find distinct rows with the following details class : Scountry 我必须使用以下详细信息类查找不同的行:Scountry
columns: countryID, countryName,isactive 列:countryID,countryName,isactive
There is no primary key in this. 在此没有主键。 I have succeeded with the followin queries 我已经成功完成了后续查询

public DbSet<SCountry> country { get; set; }
    public List<SCountry> DoDistinct()
    {
        var query = (from m in country group m by new { m.CountryID, m.CountryName, m.isactive } into mygroup select mygroup.FirstOrDefault()).Distinct();
        var Countries = query.ToList().Select(m => new SCountry { CountryID = m.CountryID, CountryName = m.CountryName, isactive = m.isactive }).ToList();
        return Countries;
    }

Interestingly enough I tried both of these in LinqPad and the variant using group from Dmitry Gribkov by appears to be quicker. 有趣的是,我在LinqPad中尝试了这两种方法,并且使用Dmitry Gribkov by的小组使用的变体似乎更快。 (also the final distinct is not required as the result is already distinct. (也不需要最后的区别,因为结果已经是不同的了。

My (somewhat simple) code was: 我的(有点简单)代码是:

public class Pair 
{ 
    public int id {get;set;}
    public string Arb {get;set;}
}

void Main()
{

    var theList = new List<Pair>();
    var randomiser = new Random();
    for (int count = 1; count < 10000; count++)
    {
        theList.Add(new Pair 
        {
            id = randomiser.Next(1, 50),
            Arb = "not used"
        });
    }

    var timer = new Stopwatch();
    timer.Start();
    var distinct = theList.GroupBy(c => c.id).Select(p => p.First().id);
    timer.Stop();
    Debug.WriteLine(timer.Elapsed);

    timer.Start();
    var otherDistinct = theList.Select(p => p.id).Distinct();
    timer.Stop();
    Debug.WriteLine(timer.Elapsed);
}

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

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