ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

Replace

Use this extention method with a lambda expression to replace the first item that satisfies the condition

Source

public static IEnumerable<TSource> Replace<TSource, Tkey>(this IList<TSource> source, TSource replacement, Func<TSource, Tkey> selector)
{
    foreach (var item in source)
    {
        var key = selector(item);

        if (key.Equals(true))
        {
            int index = source.IndexOf(item);
            source.Remove(item);
            source.Insert(index, replacement);
            break;
        }
    }
    return source;
}

Example

public static void BookReplace()
{
    var books = new List<Book>
    {
        new Book { Author = "Robert Martin", Title = "Clean Code", Pages = 464 },
        new Book { Author = "Oliver Sturm", Title = "Functional Programming in C#", Pages = 270 },
        new Book { Author = "Martin Fowler", Title = "Patterns of Enterprise Application Architecture", Pages = 533 },
        new Book { Author = "Bill Wager", Title = "Effective C#", Pages = 328 },
    };

    Book replacementBook = new Book
    {
        Author = "Test",
        Pages = 152,
        Title = "Once upon a test"
    };

    books.Replace(replacementBook, item => item.Author == "Bill Wager");
}

Author: Brecht Bocket

Submitted on: 24 jun 2016

Language: C#

Type: System.Collections.Generic.IList<T>

Views: 3885