
假设我有一个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,"and value-")); myTuple.Add(new Tuple<string,"again value-")); myTuple.Add(new Tuple<string,string>("2","another value-")); myTuple.Add(new Tuple<string,"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,而值与先前值相同全部内容,希望文章能够帮你解决c# – Foreach,而值与先前值相同所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)