gpt4 book ai didi

c# - 如何减少 'foreach' 中的相同字符串?

转载 作者:行者123 更新时间:2023-11-30 19:40:03 25 4
gpt4 key购买 nike

我是新编程,遇到这个问题,我无法得到我想做的事情,这是我的代码

foreach(RunePage rune in runePages)
{
if(rune.Slots != null && rune.Slots.Count > 0)
{
foreach(RuneSlot runeSlot in rune.Slots)
{
var runeName = staticApi.GetRune(RiotSharp.Region.lan, runeSlot.RuneId, RuneData.tags, Language.es_ES).Name;
richTextBox1.Text = runeName + "\n" + richTextBox1.Text;
}
}
richTextBox1.Text = rune.Name + "\n" + richTextBox1.Text;
}

输出:

AP

Greater Quintessence of Ability Power

Greater Quintessence of Ability Power

Greater Quintessence of Ability Power

Greater Glyph of Ability Power

Greater Glyph of Magic Resist

Greater Glyph of Ability Power

Greater Glyph of Magic Penetration

Greater Glyph of Magic Penetration

Greater Glyph of Magic Penetration

Greater Glyph of Magic Penetration

Greater Glyph of Magic Penetration

Greater Glyph of Magic Penetration

Greater Seal of Ability Power

Greater Seal of Ability Power

Greater Seal of Ability Power

Greater Seal of Armor

Greater Seal of Armor

Greater Seal of Armor

Greater Seal of Armor

Greater Seal of Armor

Greater Seal of Armor

Greater Mark of Magic Penetration

Greater Mark of Magic Penetration

Greater Mark of Magic Penetration

Greater Mark of Magic Penetration

Greater Mark of Magic Penetration

Greater Mark of Magic Penetration

Greater Mark of Magic Penetration

Greater Mark of Magic Penetration

Greater Mark of Magic Penetration

我想要的就是这样的输出

AP

3x Greater Quintessence of Ability Power

2x Greater Glyph of Ability Power

1x Greater Glyph of Magic Resist

6x Greater Glyph of Magic Penetration

3x Greater Seal of Ability Power

6x Greater Seal of Armor

9x Greater Mark of Magic Penetration

我该怎么做?

最佳答案

我建议使用 LINQ 对它们进行分组和计数:

// TODO: Build up the whole string, and set the Text property once.
// Oh, and rename richTextBox1 to something more descriptive.
foreach (RunePage rune in runePages)
{
if (rune.Slots != null)
{
var grouped = rune.Slots
.GroupBy(slot => slot.RuneId)
.Select(group => new { Name = staticApi.GetRune(RiotSharp.Region.lan,
group.Key, RuneData.tags,
Language.es_ES).Name),
Count = group.Count() })
.Select(pair => string.Format("{0}x {1}", pair.Count, pair.Name));
richTextBox1.Text = string.Join("\n", grouped);
}
richTextBox1.Text = rune.Name + "\n" + richTextBox1.Text;
}

关于c# - 如何减少 'foreach' 中的相同字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25107984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com