i have a collection of elements sorted by the elements’ Name property. i need to insert a new element into the collection while maintaining the order. i am looking for a concise LINQ way to do this. my code is below. “this.Children” is the collection, and “d” is the new element that i need to insert. it takes two passes over the collection to find the insertion point. is there a way to get the index from the First() extension method? (please do not suggest using foreach, i know that :), i am learning LINQ).
thanks!
konstantin
var v = this.Children.FirstOrDefault(x => string.Compare(x.Name, d.Name) > 0);
int index = this.Children.IndexOf(v);
if (index < 0)
{
this.children.Add(d);
}
else
{
this.Children.Insert(index, d);
}
Yes, using the overload of
Selectwhich includes the index as well as the value:Note that this is still inefficient though – if you already know the values are sorted, you can use a binary chop to find out the insertion index. It’s hard to give sample code for that without knowing the type of
Childrenthough… there’s alreadyList<T>.BinarySearchandArray.BinarySearch.Learning LINQ is admirable – but it’s also important to learn when using LINQ isn’t the best way to go 🙂