繁体   English   中英

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

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

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

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

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

具有独特的类别:

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

简单容易

我必须使用以下详细信息类查找不同的行: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;
    }

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

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

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