Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Edit a List<Tuple> item

Tags:

c#

list

tuples

With a List<String> you can edit an item simply with this:

var index = List.FindIndex(s => s.Number == box.Text);
List[index] = new String;

But, how to apply it on a List<Tuple<string, string>> for example?

like image 878
Enumy Avatar asked Oct 04 '14 02:10

Enumy


People also ask

Can we modify tuple in list?

Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called. But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.

How do you add value to a tuple?

Use the + operator to add a value to a tuple Add parentheses around the added value with a comma before the right parentheses to make it a tuple with one value. Use concatenation to add the previous tuple to the end of the original tuple to create a new tuple with an added value at the end.

Can I add elements into a list present inside a tuple?

You can't add elements to a tuple because of their immutable property. There's no append() or extend() method for tuples, You can't remove elements from a tuple, also because of their immutability.


2 Answers

You can find the index in a similar way - by applying a condition to each tuple from the list:

var index = listOfTuples.FindIndex(t => t.Item1 == box1.Text || t.Item2 == box2.Text);

You can replace an item by calling Tuple.Create:

listOfTuples[index] = Tuple.Create(box3.Text, box4.Text);
like image 151
Sergey Kalinichenko Avatar answered Oct 21 '22 10:10

Sergey Kalinichenko


var tuple = List.Find(s => s.Item1 == box.Text); 
//assuming you're searching for the first string, but you can change the predicate anyway. 
tuple = new Tuple<string, string>(new String, tuple.Item2);

As mentioned in the other answer, you can of course use the index too, but you can also just find the object and update it, that should work as well.

like image 28
AD.Net Avatar answered Oct 21 '22 10:10

AD.Net