0

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"

Result should be following:

List 1:

{"Name", "xx"},{"Age", "25"},{"PostalCode", "12345"}

List 2:

{"Name", "yy"},{"Age", "30"},{"PostalCode", "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. But there must be a better and faster way of doing this?

3
  • 4
    Why wouldn't you create a simple class that holds your data? Commented Feb 28, 2018 at 12:26
  • 1
    These tuples are of different types, <string, string> or <string, int> how you keep them originally? Commented Feb 28, 2018 at 12:33
  • I have edited my question. List contains a tuple of <string, string>. Am getting data like this from an external interface. Commented Feb 28, 2018 at 12:43

2 Answers 2

4

You can use LINQ to find all the indices of Name and select it and the following 3 entries into a new list.

This assumes that the original list is well-formed such that for every Name there is guaranteed to be two valid fields following it.

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use Enumrable.Range to loop trough your list and select your desired tuples:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.