Map and Reduce in .NET

前端 未结 3 1250
北恋
北恋 2020-12-04 05:42

What scenarios would warrant the use of the \"Map and Reduce\" algorithm?


Is there a .NET implementation of this algorithm?

3条回答
  •  醉酒成梦
    2020-12-04 06:15

    Since I never can remember that LINQ calls it Where, Select and Aggregate instead of Filter, Map and Reduce so I created a few extension methods you can use:

    IEnumerable myStrings = new List() { "1", "2", "3", "4", "5" };
    IEnumerable convertedToInts = myStrings.Map(s => int.Parse(s));
    IEnumerable filteredInts = convertedToInts.Filter(i => i <= 3); // Keep 1,2,3
    int sumOfAllInts = filteredInts.Reduce((sum, i) => sum + i); // Sum up all ints
    Assert.Equal(6, sumOfAllInts); // 1+2+3 is 6
    

    Here are the 3 methods (from https://github.com/cs-util-com/cscore/blob/master/CsCore/PlainNetClassLib/src/Plugins/CsCore/com/csutil/collections/IEnumerableExtensions.cs ):

    public static IEnumerable Map(this IEnumerable self, Func selector) {
        return self.Select(selector);
    }
    
    public static T Reduce(this IEnumerable self, Func func) {
        return self.Aggregate(func);
    }
    
    public static IEnumerable Filter(this IEnumerable self, Func predicate) {
        return self.Where(predicate);
    }
    

    Some more details from https://github.com/cs-util-com/cscore#ienumerable-extensions :

提交回复
热议问题