本文介绍了如何动态编辑对象linq C#列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    List<Scorer> hScorers;

    private void button_Click(object sender, RoutedEventArgs e)
    {

        hScorers = new List<Scorer>();
        hScorers.Add(new Scorer() { PlayerRef = "joe", Time = "2'"});
        hScorers.Add(new Scorer() { PlayerRef = "moe", Time = "2'" });
        hScorers.Add(new Scorer() { PlayerRef = "joe", Time = "5'" });
        hScorers.Add(new Scorer() { PlayerRef = "roe", Time = "2'" });
        hScorers.Add(new Scorer() { PlayerRef = "joe", Time = "8'" });
        hScorers.Add(new Scorer() { PlayerRef = "joe", Time = "3'" });

        int count = 0;
        foreach (var v in hScorers)
        {
                if (v.PlayerRef == hScorers[0].PlayerRef)
                {
                    if (count != 0)
                    {
                        hScorers[0].Time = hScorers[0].Time + ", " + v.Time;
                        v.PlayerRef = "";
                        v.Time = "";
                    }                     
                }
            count++;
        }
        hScorers.Where(x => x.PlayerRef == "")
            .ToList()
            .ForEach(x =>
            {
                if (x.PlayerRef == "")
                {
                    hScorers.Remove(x);
                }
            });            
        foreach (var scorer in hScorers)
        {
            listBox.Items.Add(scorer.PlayerRef + " "+ scorer.Time);
        }
    }

我想实现的目标是有四位选手的裁判为"joe",因此在对象列表中,我希望有一位选手的选手的裁判为"joe",因此,如果存在该选手,则格式为

what I would like to achieve is for e.g. there are four players with the ref of "joe" so in the list of object I would like to have one player with the playerref of "joe" so if the player exist the format will be

playerref ="joe"时间= 2',3',5',8'

playerref = "joe" Time = 2', 3', 5', 8'

,或者如果有一名玩家,则:playerref ="moe"时间= 2'

or if one player its:playerref = "moe" Time = 2'

此代码可以执行我想要的操作,但它不是动态的.因为我已经使用hScorers [0] .PlayerRef对其进行了硬编码.我希望它不仅可以过滤hScorers [0] .PlayerRef,还可以过滤所有可能的播放器.因此,如果列表中有5个玩家使用(编辑列表;简而言之,我想删除重复的玩家并在其中添加时间到现有实例中):

This code does what I want it to do but its not dynamic. Because I have hard-coded it using hScorers[0].PlayerRef. Instead of just hScorers[0].PlayerRef I would like it to filter with all the possible players. So if there is 5 players in the list it uses(to edit the list; in short I would like to remove duplicate players and add there time to the existing instance):

hScorers[0].PlayerRef
hScorers[1].PlayerRef
hScorers[2].PlayerRef
hScorers[3].PlayerRef
hScorers[4].PlayerRef

推荐答案

使用Linq的GroupBy.应该执行以下操作:

Use Linq's GroupBy. The following should do the job:

hScorers = hScorers
    .GroupBy(s => s.PlayerRef)
    .Select(g => new Scorer { PlayerRef = g.Key, Time = string.Join(", ", g.Select(v => v.Time)) })
    .ToList();

这篇关于如何动态编辑对象linq C#列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 19:38