我很难解释这个问题,但我认为这是我们许多人遇到的普遍问题。
假设我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();
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句