c# – Foreach,而值与先前值相同
发布时间:2020-12-16 02:00:22 所属栏目:百科 来源:网络整理
导读:我发现很难解释这个问题,但我认为这是我们很多人遇到的常见问题. 假设我有一个List string,string采用以下格式: 1,value-1,and value-1,again value-2,another value-2,yet another value- 我想将其转换为List string这将只包含2个项目 value-and value-aga
我发现很难解释这个问题,但我认为这是我们很多人遇到的常见问题.
假设我有一个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(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |