首页 > 代码库 > C#版的MapReduce
C#版的MapReduce
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace mapReduce { public static class helper { public static Dictionary<TKey, TResult> MapReduce<TInput, TKey, TValue, TResult>( this IEnumerable<TInput> list, //Func<TInput, IEnumerable<KeyValuePair<TKey, TValue>>> map, Func<TInput, KeyValuePair<TKey, TValue>> map, Func<TKey, IEnumerable<TValue>, TResult> reduce) { Dictionary<TKey, List<TValue>> mapResult = new Dictionary<TKey, List<TValue>>(); foreach (var item in list) { //foreach (var one in map(item)) //{ var one = map(item); if (Convert.ToInt32( one.Key) == 0) { continue; } List<TValue> mapValues; if (!mapResult.TryGetValue(one.Key, out mapValues)) { mapValues = new List<TValue>(); mapResult.Add(one.Key, mapValues); } mapValues.Add(one.Value); //} } var result = new Dictionary<TKey, TResult>(); foreach (var m in mapResult) { result.Add(m.Key, reduce(m.Key, m.Value)); } return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace mapReduce { class Program { static void Main(string[] args) { List<Person> list = new List<Person>(); list.Add(new Person { ID = 1, Name = "肖银龙", Age = 23 }); list.Add(new Person { ID = 2, Name = "郭彦磊", Age = 24 }); list.Add(new Person { ID = 3, Name = "王老师", Age = 23 }); list.Add(new Person { ID = 4, Name = "路人甲", Age = 25 }); list.Add(new Person { ID = 5, Name = "路人乙", Age = 20 }); var result = list.MapReduce<Person, int, string, string>(Map, (key, values) => string.Join(",", values)); foreach (var d in result) { Console.WriteLine(d.Key + ":" + d.Value); } Console.Read(); } //public static IEnumerable<KeyValuePair<int, string>> Map(Person p) //{ // if (p.Age > 22) // yield return new KeyValuePair<int, string>(p.Age, p.Name); //} public static KeyValuePair<int, string> Map(Person p) { if (p.Age > 22) return new KeyValuePair<int, string>(p.Age, p.Name); else return new KeyValuePair<int, string>(0,null); } } public class Person { public int ID { get; set; } public string Name { get; set; } public int Age { get; set; } } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。