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

时间:2013-10-23 17:09:16

标签: c# linq visual-studio-2012 csv asp.net-web-api

我在VS 2012中创建了一个Web Api。 我试图从一列“类别”中获取所有值,这是所有唯一值,我不希望列表返回重复项。

我使用此代码获取特定类别的产品。如何获取完整的类别列表(类别列中的所有唯一值)?

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

4 个答案:

答案 0 :(得分:57)

拥有独特的类别:

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

答案 1 :(得分:16)

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

简单易用

答案 2 :(得分:1)

我必须找到具有以下细节的不同行 class: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;
    }

答案 3 :(得分:0)

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

我的代码(有点简单)是:

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