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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19548043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 15:15:56  来源:igfitidea点击:

Select All distinct values in a column using LINQ

c#linqvisual-studio-2012csvasp.net-web-api

提问by Tester

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));
    }

采纳答案by Alireza

To have unique Categories:

拥有独特的类别:

var uniqueCategories =  repository.GetAllProducts()
                                  .Select(p=>p.Category)
                                  .Distinct();

回答by Dmitry Gribkov

var uniq = allvalues.GroupBy(x => x.Id).Select(y=>y.First()).Distinct();

Easy and simple

简单易行

回答by Basant tiwari

I have to find distinct rows with the following details class : Scountry
columns: countryID, countryName,isactive
There is no primary key in this. I have succeeded with the followin queries

我必须找到具有以下详细信息类的不同行: Scountry
列:countryID、countryName、isactive
这里没有主键。我已成功完成以下查询

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;
    }

回答by Drew

Interestingly enough I tried both of these in LinqPad and the variant using group from Dmitry Gribkov by appears to be quicker. (also the final distinct is not required as the result is already distinct.

有趣的是,我在 LinqPad 中尝试了这两种方法,使用 Dmitry Gribkov 的 group 的变体似乎更快。(也不需要最终的不同,因为结果已经不同。

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);
}