C#: Altering values for every item in an array

前端 未结 6 1329
醉梦人生
醉梦人生 2020-12-30 01:54

I\'m wondering if there is built-in .NET functionality to change each value in an array based on the result of a provided delegate. For example, if I had an array {1,

6条回答
  •  醉话见心
    2020-12-30 02:36

    Here is another solution for M x N arrays, where M and N are not known at compile time.

        // credit: https://blogs.msdn.microsoft.com/ericlippert/2010/06/28/computing-a-cartesian-product-with-linq/
        public static IEnumerable> CartesianProduct(IEnumerable> sequences)
        {
            IEnumerable> result = new[] { Enumerable.Empty() };
            foreach (var sequence in sequences)
            {
                // got a warning about different compiler behavior
                // accessing sequence in a closure
                var s = sequence;
                result = result.SelectMany(seq => s, (seq, item) => seq.Concat(new[] { item }));
            }
            return result;
        }
    
    
        public static void ConvertInPlace(this Array array, Func projection)
        {
            if (array == null)
            {
                return;
            }
    
            // build up the range for each dimension
            var dimensions = Enumerable.Range(0, array.Rank).Select(r => Enumerable.Range(0, array.GetLength(r)));
    
            // build up a list of all possible indices
            var indexes = EnumerableHelper.CartesianProduct(dimensions).ToArray();
    
            foreach (var index in indexes)
            {
                var currentIndex = index.ToArray();
                array.SetValue(projection(array.GetValue(currentIndex)), currentIndex);
            }
        }
    

提交回复
热议问题