How to replace list item in best way

前端 未结 11 2226
天涯浪人
天涯浪人 2020-11-30 21:52
if (listofelements.Contains(valueFieldValue.ToString()))
{
    listofelements[listofelements.IndexOf(valueFieldValue.ToString())] = value.ToString();
}
11条回答
  •  隐瞒了意图╮
    2020-11-30 22:51

    Why not use the extension methods?

    Consider the following code:

            var intArray = new int[] { 0, 1, 1, 2, 3, 4 };
            // Replaces the first occurance and returns the index
            var index = intArray.Replace(1, 0);
            // {0, 0, 1, 2, 3, 4}; index=1
    
            var stringList = new List { "a", "a", "c", "d"};
            stringList.ReplaceAll("a", "b");
            // {"b", "b", "c", "d"};
    
            var intEnum = intArray.Select(x => x);
            intEnum = intEnum.Replace(0, 1);
            // {0, 0, 1, 2, 3, 4} => {1, 1, 1, 2, 3, 4}
    
    • No code duplication
    • There is no need to type long linq expressions
    • There is no need for additional usings

    The source code:

    namespace System.Collections.Generic
    {
        public static class Extensions
        {
            public static int Replace(this IList source, T oldValue, T newValue)
            {
                if (source == null)
                    throw new ArgumentNullException(nameof(source));
    
                var index = source.IndexOf(oldValue);
                if (index != -1)
                    source[index] = newValue;
                return index;
            }
    
            public static void ReplaceAll(this IList source, T oldValue, T newValue)
            {
                if (source == null)
                    throw new ArgumentNullException(nameof(source));
    
                int index = -1;
                do
                {
                    index = source.IndexOf(oldValue);
                    if (index != -1)
                        source[index] = newValue;
                } while (index != -1);
            }
    
    
            public static IEnumerable Replace(this IEnumerable source, T oldValue, T newValue)
            {
                if (source == null)
                    throw new ArgumentNullException(nameof(source));
    
                return source.Select(x => EqualityComparer.Default.Equals(x, oldValue) ? newValue : x);
            }
        }
    }
    

    The first two methods have been added to change the objects of reference types in place. Of course, you can use just the third method for all types.

    P.S. Thanks to mike's observation, I've added the ReplaceAll method.

提交回复
热议问题