如何使用 LINQ 计算列表中的重复项 [英] How to Count Duplicates in List with LINQ

查看:29
本文介绍了如何使用 LINQ 计算列表中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个物品清单

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

我想将它们推回到这样的列表中,这也意味着我想按重复次数最多的顺序排序.

I want to shove them back into a list like so which also means I want to sort by the highest number of duplicates.

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

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

Let me know how I can do this with LINQ and 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 hello world Times
  • 1 hello world Times
  • 1 Hello World.
  • 1 hello world Times
  • 1 hello world Times
  • 1 hello world Times
  • 1 Hello World.
  • 1 hello world Times

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

It gives me the count and name, but it doesn't give me the ID of the game....

它应该显示:

  • 6 hello world Times 234234
  • 2 你好世界.23432432

推荐答案

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

You can use "group by" + "orderby". See LINQ 101 for details

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

回应这篇文章(现已删除):

In response to this post (now deleted):

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

If you have a list of some custom objects then you need to use custom comparer or group by specific property.

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

Also query can't display result. Show us complete code to get a better help.

基于您的最新更新:

你有这行代码:

group xx by xx into g

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

Since xx is a custom object system doesn't know how to compare one item against another. As I already wrote, you need to guide compiler and provide some property that will be used in objects comparison or provide custom comparer. Here is an example:

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

Note that I use Foo.Name as a key - i.e. objects will be grouped based on value of Name property.

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

There is one catch - you treat 2 objects to be duplicate based on their names, but what about Id ? In my example I just take Id of the first object in a group. If your objects have different Ids it can be a problem.

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

这篇关于如何使用 LINQ 计算列表中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆