How to replace list item in best way

前端 未结 11 2211
天涯浪人
天涯浪人 2020-11-30 21:52
if (listofelements.Contains(valueFieldValue.ToString()))
{
    listofelements[listofelements.IndexOf(valueFieldValue.ToString())] = value.ToString();
}
相关标签:
11条回答
  • 2020-11-30 22:52

    I don't if it is best or not but you can use it also

    List<string> data = new List<string>
    (new string[]   { "Computer", "A", "B", "Computer", "B", "A" });
    int[] indexes = Enumerable.Range(0, data.Count).Where
                     (i => data[i] == "Computer").ToArray();
    Array.ForEach(indexes, i => data[i] = "Calculator");
    
    0 讨论(0)
  • 2020-11-30 22:52

    Or, building on Rusian L.'s suggestion, if the item you're searching for can be in the list more than once::

    [Extension()]
    public void ReplaceAll<T>(List<T> input, T search, T replace)
    {
        int i = 0;
        do {
            i = input.FindIndex(i, s => EqualityComparer<T>.Default.Equals(s, search));
    
            if (i > -1) {
                FileSystem.input(i) = replace;
                continue;
            }
    
            break;  
        } while (true);
    }
    
    0 讨论(0)
  • 2020-11-30 22:53

    i find best for do it fast and simple

    1. find ur item in list

      var d = Details.Where(x => x.ProductID == selectedProduct.ID).SingleOrDefault();
      
    2. make clone from current

      OrderDetail dd = d;
      
    3. Update ur clone

      dd.Quantity++;
      
    4. find index in list

      int idx = Details.IndexOf(d);
      
    5. remove founded item in (1)

        Details.Remove(d);
      
    6. insert

       if (idx > -1)
            Details.Insert(idx, dd);
        else
            Details.Insert(Details.Count, dd);
      
    0 讨论(0)
  • 2020-11-30 22:55

    Use Lambda to find the index in the List and use this index to replace the list item.

    List<string> listOfStrings = new List<string> {"abc", "123", "ghi"};
    listOfStrings[listOfStrings.FindIndex(ind=>ind.Equals("123"))] =  "def";
    
    0 讨论(0)
  • 2020-11-30 22:56

    You can use the next extensions which are based on a predicate condition:

        /// <summary>
        /// Find an index of a first element that satisfies <paramref name="match"/>
        /// </summary>
        /// <typeparam name="T">Type of elements in the source collection</typeparam>
        /// <param name="this">This</param>
        /// <param name="match">Match predicate</param>
        /// <returns>Zero based index of an element. -1 if there is not such matches</returns>
        public static int IndexOf<T>(this IList<T> @this, Predicate<T> match)
        {
            @this.ThrowIfArgumentIsNull();
            match.ThrowIfArgumentIsNull();
    
            for (int i = 0; i < @this.Count; ++i)
                if (match(@this[i]))
                    return i;
    
            return -1;
        }
    
        /// <summary>
        /// Replace the first occurance of an oldValue which satisfies the <paramref name="removeByCondition"/> by a newValue
        /// </summary>
        /// <typeparam name="T">Type of elements of a target list</typeparam>
        /// <param name="this">Source collection</param>
        /// <param name="removeByCondition">A condition which decides is a value should be replaced or not</param>
        /// <param name="newValue">A new value instead of replaced</param>
        /// <returns>This</returns>
        public static IList<T> Replace<T>(this IList<T> @this, Predicate<T> replaceByCondition, T newValue)
        {
            @this.ThrowIfArgumentIsNull();
            removeByCondition.ThrowIfArgumentIsNull();
    
            int index = @this.IndexOf(replaceByCondition);
            if (index != -1)
                @this[index] = newValue;
    
            return @this;
        }
    
        /// <summary>
        /// Replace all occurance of values which satisfy the <paramref name="removeByCondition"/> by a newValue
        /// </summary>
        /// <typeparam name="T">Type of elements of a target list</typeparam>
        /// <param name="this">Source collection</param>
        /// <param name="removeByCondition">A condition which decides is a value should be replaced or not</param>
        /// <param name="newValue">A new value instead of replaced</param>
        /// <returns>This</returns>
        public static IList<T> ReplaceAll<T>(this IList<T> @this, Predicate<T> replaceByCondition, T newValue)
        {
            @this.ThrowIfArgumentIsNull();
            removeByCondition.ThrowIfArgumentIsNull();
    
            for (int i = 0; i < @this.Count; ++i)
                if (replaceByCondition(@this[i]))
                    @this[i] = newValue;
    
            return @this;
        }
    

    Notes: - Instead of ThrowIfArgumentIsNull extension, you can use a general approach like:

    if (argName == null) throw new ArgumentNullException(nameof(argName));
    

    So your case with these extensions can be solved as:

    string targetString = valueFieldValue.ToString();
    listofelements.Replace(x => x.Equals(targetString), value.ToString());
    
    0 讨论(0)
提交回复
热议问题