如何使用 LINQ 根据对象列表中的属性计算重复项

问题描述 投票:0回答:8

我有一份物品清单

  • 约翰·ID
  • 马特ID
  • 约翰·ID
  • 斯科特ID
  • 马特ID
  • 约翰·ID
  • 卢卡斯ID

我想将它们推回到列表中,就像这样,这也意味着我想按重复项的最高数量进行排序。

  • 约翰 ID 3
  • 马特ID 2
  • 斯科特 ID 1
  • 卢卡斯 ID 1

让我知道如何使用 LINQ 和 C# 来做到这一点。

谢谢大家

编辑2显示代码:

    List<game> inventory = new List<game>();
    drinkingforDataContext db = new drinkingforDataContext();
    foreach (string item in tbTitle.Text.Split(' '))
    {

        List<game> getItems = (from dfg in db.drinkingfor_Games
                               where dfg.game_Name.Contains(tbTitle.Text)
                               select new game
                               {
                                   gameName = dfg.game_Name,
                                   gameID = Boomers.Utilities.Guids.Encoder.EncodeURLs(dfg.uid)
                               }).ToList<game>();

        for (int i = 0; i < getItems.Count(); i++)
        {
            inventory.Add(getItems[i]);
        }
    }

    var items = (from xx in inventory
                 group xx by xx into g
                 let count = g.Count()
                 orderby count descending
                 select new
                    {
                        Count = count,
                        gameName = g.Key.gameName,
                        gameID = g.Key.gameID
                    });

    lvRelatedGames.DataSource = items;
    lvRelatedGames.DataBind();

此查询显示以下结果:

  • 1 你好世界时报
  • 1 你好世界时报
  • 1 世界你好。
  • 1 你好世界时报
  • 1 你好世界时报
  • 1 你好世界时报
  • 1 世界你好。
  • 1 你好世界时报

它给了我计数和名称,但它没有给我游戏的ID....

它应该显示:

  • 6 你好世界时报234234
  • 2 世界你好。 23432432
c# linq
8个回答
114
投票

您可以使用“group by”+“orderby”。有关详细信息,请参阅 LINQ 101

var list = new List<string> {"a", "b", "a", "c", "a", "b"};
var q = from x in list
        group x by x into g
        let count = g.Count()
        orderby count descending
        select new {Value = g.Key, Count = count};
foreach (var x in q)
{
    Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
}

回复此帖子(现已删除):

如果您有一些自定义对象的列表,那么您需要使用自定义比较器或按特定属性进行分组。

查询也无法显示结果。向我们展示完整的代码以获得更好的帮助。

基于您的最新更新:

你有这行代码:

group xx by xx into g

由于 xx 是一个自定义对象系统,因此不知道如何将一个项目与另一个项目进行比较。 正如我已经写过的,您需要指导编译器并提供一些将在对象比较中使用的属性或提供自定义比较器。这是一个例子:

请注意,我使用 Foo.Name 作为键 - 即对象将根据 Name 属性的值进行分组。

有一个问题 - 您根据 2 个对象的名称将其视为重复,但是 Id 呢?在我的示例中,我只获取组中第一个对象的 ID。如果您的对象具有不同的 ID,则可能会出现问题。

//Using extension methods
var q = list.GroupBy(x => x.Name)
            .Select(x => new {Count = x.Count(), 
                              Name = x.Key, 
                              ID = x.First().ID})
            .OrderByDescending(x => x.Count);

//Using LINQ
var q = from x in list
        group x by x.Name into g
        let count = g.Count()
        orderby count descending
        select new {Name = g.Key, Count = count, ID = g.First().ID};

foreach (var x in q)
{
    Console.WriteLine("Count: " + x.Count + " Name: " + x.Name + " ID: " + x.ID);
}

64
投票

使用方法链的稍短版本:

var list = new List<string> {"a", "b", "a", "c", "a", "b"};
var q = list.GroupBy(x => x)
            .Select(g => new {Value = g.Key, Count = g.Count()})
            .OrderByDescending(x=>x.Count);

foreach (var x in q)
{
    Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
}

9
投票

您还可以做词典:

 var list = new List<string> { "a", "b", "a", "c", "a", "b" };
 var result = list.GroupBy(x => x)
            .ToDictionary(y=>y.Key, y=>y.Count())
            .OrderByDescending(z => z.Value);

 foreach (var x in result)
        {
            Console.WriteLine("Value: " + x.Key + " Count: " + x.Value);
        }

8
投票

其他解决方案使用

GroupBy
GroupBy
很慢(它保存了内存中的所有元素),所以我写了自己的方法
CountBy

public static Dictionary<TKey,int> CountBy<TSource,TKey>(this IEnumerable<TSource> source, Func<TSource,TKey> keySelector)
{
    var countsByKey = new Dictionary<TKey,int>();
    foreach(var x in source)
    {
        var key = keySelector(x);
        if (!countsByKey.ContainsKey(key))
            countsByKey[key] = 0;
        countsByKey[key] += 1;
    }
    return countsByKey;
}

1
投票

为什么不发布新答案!如今,我认为你可以做类似的事情......

var duplicatesCount = listVariable.Count(o => o.Equals(listElement));

然后只需在新列表中添加具有重复计数的每个元素,并使用
!listVariable.Contains(elem)
重复拦截器


-1
投票

另一种解决方案

public static void Main()
{
        var list = new List<string> {"a", "b", "a", "c", "a", "b"};
        list.GroupBy(x => x)
            .Select(x => new { Value = x.Key, Count = x.Count()} )
            .Where(x => x.Count > 1).ToList()
            .ForEach(x => Console.WriteLine($"Value: {x.Value} Count: {x.Count}"));
}

-2
投票

这是完整的程序请检查这个

static void Main(string[] args)
{
    List<string> li = new List<string>();
    li.Add("Ram");
    li.Add("shyam");
    li.Add("Ram");
    li.Add("Kumar");
    li.Add("Kumar");

    var x = from obj in li group obj by obj into g select new { Name = g.Key, Duplicatecount = g.Count() };
    foreach(var m in x)
    {
        Console.WriteLine(m.Name + "--" + m.Duplicatecount);
    }
    Console.ReadLine();
}        

-2
投票
**Here is the complete program without using any LINQ or nested Loops**

    using System;
    using System.Collections.Generic;
    using System.Linq;
                        
    public class Program
    {
        
        public static void Main()
        {
            List<string> listItems = new List<string>();
            int[] result = {0,2,1,0,3,2,1};
            var arrayValue = new List<int>();
            foreach(var x in result){
                if(!arrayValue.Contains(x)){
                    arrayValue.Add(x);
                    var countVal = findArrayCount(x);
                    listItems.Add("value :" + x  + "Count:" + countVal);
                }
            }
            listItems.ForEach(li => Console.WriteLine(li));
        }

        public static int findArrayCount(int x) {
          int[] result = {0,2,1,0,3,2,1};
          int countval = 0;
          foreach (var val in result)
          {
            if(val.Equals(x)){ countval+=1;}
          }
          return countval;
        }
}
    
    OutPut:
    value :0 Count:2
    value :2 Count:2
    value :1 Count:2
    value :3 Count:1
© www.soinside.com 2019 - 2024. All rights reserved.