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

59

我在VS 2012中创建了一个Web Api。我试图获取一列“Category”中的所有值,即所有唯一值,我不希望返回包含重复项的列表。

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

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

你的问题对我来说不太清楚,当你通过类别“获取产品”时,当然你得到的“产品”应该具有相同的“类别”,这里有什么不同之处? - King King
是的,这段代码用于按指定类别获取产品,但我想修改它以获取完整的类别列表。GetCatgoriesList()。类别是产品表中的一列,因此该列中会有重复值,因为它与每个产品相关。我想要的是用于对表中产品进行分类的类别列表。 - Tester
2
如果是这样,下面的答案应该可以工作,但请注意返回结果是一个 IEnumerable<string>,您可以通过迭代来打印完整的“不同类别”列表。 - King King
公共 IEnumerable<Product> GetAllCategory() { 返回 repository.GetAllProducts() .Select(p => p.Category).Distinct(); } -- 我尝试了这个,但我仍然得到构建错误 - Tester
2
你需要将 public IEnumerable<Product> 改为 public IEnumerable<string> - King King
这就是关系型数据库的目的!设计并使用一个“类别”模型/表。 - dwerner
4个回答

110

拥有独特的分类:

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

1
我尝试了这个,但是出现了一个构建错误:无法隐式转换类型 'System.Collections.Generic.IEnumerable<string>' 到 'System.Collections.Generic.IEnumerable<TestService.Models.Product>'。存在一个显式转换(你是否忘记了进行强制转换?) - Tester
1
@测试人员,请查看King King在问题上的评论。 - Alireza
太棒了,这个方法对我有用,我能够从重复的数据中选择一个不同的类别列表!!!非常感谢。 - PatsonLeaner

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

易学易懂


1
当使用Ienumerables / Lists时,这似乎是更好的方法。这对我有用:var details = allDetails .Where(x => x.EmpId == 100) .GroupBy(x => x.SaleDate).Select(y => y.First()).Distinct(); - Venugopal M
很棒的解决方案。 - Raju Paladiya

2

我需要找到具有以下细节的不同行:

类别: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;
    }

0
有趣的是,我在 LinqPad 中尝试了这两个变体,使用 Dmitry Gribkov 的 group 更快。(由于结果已经不重复,因此最终的 distinct 不是必需的。)
我的(有点简单)代码如下:
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);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接