gpt4 book ai didi

c# - Foreach while 一个值与前一个值相同

转载 作者:行者123 更新时间:2023-11-30 14:10:51 25 4
gpt4 key购买 nike

我发现很难解释这个问题,但我认为这是我们许多人遇到的常见问题。

假设我有一个 List<string, string>采用以下格式:

1, value-
1, and value-
1, again value-
2, another value-
2, yet another value-

我想将其转换为 List<string>这将只包含 2 项

value-and value-again value-
another value-yet another value

这是基于数字(1 或 2)。

我通常使用的代码有效,但似乎有些麻烦。

是否有更简洁的方法,可能是使用 Linq?

一个快速的控制台应用程序来演示我正在尝试做的事情,希望它能比我的问题更好地解释它!

class Program
{
static void Main(string[] args)
{
List<Tuple<string, string>> myTuple = new List<Tuple<string, string>>();
myTuple.Add(new Tuple<string, string>("1", "value-"));
myTuple.Add(new Tuple<string, string>("1", "and value-"));
myTuple.Add(new Tuple<string, string>("1", "again value-"));
myTuple.Add(new Tuple<string, string>("2", "another value-"));
myTuple.Add(new Tuple<string, string>("2", "yet another value"));

string previousValue = "";
string concatString = "";
List<string> result = new List<string>();
foreach (var item in myTuple)
{
if (string.IsNullOrEmpty(previousValue))
previousValue += item.Item1;

if (previousValue == item.Item1)
concatString += item.Item2;
else
{
result.Add(concatString);
concatString = "";
previousValue = item.Item1;
concatString=item.Item2;
}
}
//add the last value
result.Add(concatString);
}

最佳答案

List<string> result = myTuple.GroupBy(t => t.Item1)
.Select(g => String.Join(" ", g.Select(tp=>tp.Item2)))
.ToList();

关于c# - Foreach while 一个值与前一个值相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22071237/

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