Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending an element to a collection using LINQ

I am trying to process some list with a functional approach in C#.

The idea is that I have a collection of Tuple<T,double> and I want to change the Item 2 of some element T.

The functional way to do so, as data is immutable, is to take the list, filter for all elements where the element is different from the one to change, and the append a new tuple with the new values.

My problem is that I do not know how to append the element at the end. I would like to do:

public List<Tuple<T,double>> Replace(List<Tuple<T,double>> collection, T term,double value)
{
   return collection.Where(x=>!x.Item1.Equals(term)).Append(Tuple.Create(term,value));
}

But there is no Append method. Is there something else?

like image 718
SRKX Avatar asked Nov 18 '11 09:11

SRKX


1 Answers

I believe you are looking for the Concat operator.

It joins two IEnumerable<T> together, so you can create one with a single item to join.

public List<Tuple<T,double>> Replace(List<Tuple<T,double>> collection, T term,double value)
{
   var newItem = new List<Tuple<T,double>>();
   newItem.Add(new Tuple<T,double>(term,value));
   return collection.Where(x=>!x.Item1.Equals(term)).Concat(newItem).ToList();
}
like image 127
Oded Avatar answered Oct 12 '22 09:10

Oded