[英]c# split list of tuple into multiple lists
Assuming I have the following list of tuples: 假设我有以下元组列表:
List<Tuple<string, string>>
{"Name", "xx"},{"Age", "25"},{"PostalCode", "12345"},{"Name", "yy"},{"Age", "30"},{"PostalCode", "67890"}
I want to split this list into multiple lists. 我想将此列表拆分为多个列表。 Splitting criteria is Item1 == "Name"
拆分条件为Item1 == "Name"
Result should be following: 结果应为:
List 1: 清单1:
{"Name", "xx"},{"Age", "25"},{"PostalCode", "12345"} {“名称”,“ xx”},{“年龄”,“ 25”},{“邮政编码”,“ 12345”}
List 2: 清单2:
{"Name", "yy"},{"Age", "30"},{"PostalCode", "67890"} {“名称”,“ yy”},{“年龄”,“ 30”},{“邮政编码”,“ 67890”}
I have a solution where I note down the indexes of "Name" in the original list and create new lists by using the function GetRange
. 我有一个解决方案,其中记下了原始列表中“名称”的索引,并使用GetRange
函数创建了新列表。 But there must be a better and faster way of doing this? 但是必须有更好,更快的方法吗?
You can use LINQ to find all the indices of Name
and select it and the following 3 entries into a new list. 您可以使用LINQ查找Name
所有索引,然后选择它以及以下3个条目到新列表中。
This assumes that the original list is well-formed such that for every Name
there is guaranteed to be two valid fields following it. 假设原始列表格式正确,因此对于每个Name
,保证在其后有两个有效字段。
var data = new List<Tuple<string, string>>
{
new Tuple<string, string>("Name", "xx"),
new Tuple<string, string>("Age", "25"),
new Tuple<string, string>("PostalCode", "12345"),
new Tuple<string, string>("ignoreMe", "345"),
new Tuple<string, string>("Name", "yy"),
new Tuple<string, string>("Age", "30"),
new Tuple<string, string>("PostalCode", "67890")
};
var lists = data
.Select((x, i) => new { Index = i, Value = x })
.Where(x => x.Value.Item1 == "Name")
.Select(x => data.Skip(x.Index).Take(3))
.ToList();
And also, there are probably more performant solutions than this. 而且,可能还有比这更多的性能解决方案。
You can use Enumrable.Range
to loop trough your list and select your desired tuples: 您可以使用Enumrable.Range
遍历列表并选择所需的元组:
List<Tuple<string, string>> data = new List<Tuple<string, string>>
{
new Tuple<string, string>("Name", "xx"),
new Tuple<string, string>("Age", "25"),
new Tuple<string, string>("PostalCode", "12345"),
new Tuple<string, string>("Name", "yy"),
new Tuple<string, string>("Age", "30"),
new Tuple<string, string>("PostalCode", "67890")
};
var result = Enumerable.Range(0, data.Count).Where(i => data[i].Item1 == "Name")
.Select(i => data.Skip(i).Take(3).ToList())
.ToList();
You can test my code here : https://dotnetfiddle.net/6fJumx 您可以在这里测试我的代码: https : //dotnetfiddle.net/6fJumx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.