看了不少开发人员写的代码基本上属于LinQ出来很多年,从来没用过,其实还是非常好用的
public void Foo(){ Dictionary<int, string> frenchNumbers; frenchNumbers = new Dictionary<int, string>(); frenchNumbers.Add(0, "zero"); frenchNumbers.Add(1, "one"); frenchNumbers.Add(2, "two"); frenchNumbers.Add(3, "three"); frenchNumbers.Add(4, "four"); var evenFrenchNumbers = from entry in frenchNumbers where (entry.Key % 2) == 0 select entry.Value; }
或者
enum MyEnum : int { a, b, c, } public void foo(){ var v = Enum.GetNames(typeof(MyEnum)).Select((key, value) => new { key, value }).ToDictionary(x => x.key , x => x.value); foreach (var item in v) { Console.WriteLine(item.Key + " "+item.Value); } }
再或者
public static Dictionary<int, string> GetEnumDictionary<T>() { if (!typeof(T).IsEnum) throw new ArgumentException("T is not an Enum type"); if (Enum.GetUnderlyingType(typeof(T)) != typeof(int)) throw new ArgumentException("The underlying type of the enum T is not Int32"); return Enum.GetValues(typeof(T)) .Cast<T>() .ToDictionary(t => (int)(object)t, t => t.ToString()); }
原文:http://www.cnblogs.com/aisiyes/p/3746916.html