如何通过枚举绑定列表

use*_*355 3 c#

我试图用枚举绑定一个列表.枚举有以下价值

public enum Degree
{

    Doctorate = 1,
    Masters = 2,
    Bachelors = 3,
    Diploma = 4,
    HighSchool = 5,
    Others = 6
}
Run Code Online (Sandbox Code Playgroud)

并且列表是以下类的类型

class List1
{
    public string Text{get; set;}
    public string Value{get; set;}
}
Run Code Online (Sandbox Code Playgroud)

如何映射呢?

Sco*_*pey 6

这是一个非常简单的LINQ解决方案:

var t = typeof(Degree);
var list = Enum.GetValues(t).Cast<int>().Zip(Enum.GetNames(t), 
    (value, name) => new List1{Text = name, Value = value.ToString()}
    ).ToList();
Run Code Online (Sandbox Code Playgroud)

显然,这也可以转化为扩展方法.

有关详细信息,请参阅:
Enum.GetValues
Enum.GetNames
LINQ Enumerable.Zip

更新

由于该Zip方法仅在.NET 4.0中,因此这是另一种3.0方法.

var t = typeof(Degree);
var list = Enum.GetValues(t).Cast<Degree>().Select(
    value => new List1{ Text = value.ToString(), Value = ((int)value).ToString() }
    ).ToList();
Run Code Online (Sandbox Code Playgroud)

如果您需要2.0答案,请查看@ Dewasish的答案.