如何在C#中将字段命名添加到KeyValuePair

时间:2012-09-17 00:00:18

标签: c#

我有以下代码:

        var values1 = (EReferenceKey[])Enum.GetValues(typeof(EReferenceKey)); 
        var valuesWithNames = values1.Select(
            value => new {
                Value = ((int)value).ToString("00"),
                Text = Regex.Replace(value.ToString(), "([A-Z])", " $1").Trim() 
            });

这是在stackoverflow上建议的一些代码,可以使这个方法通用:

    public static IEnumerable<KeyValuePair<string, string>> GetValues2<T>() where T : struct {
        var t = typeof(T);
        if (!t.IsEnum)
            throw new ArgumentException("Not an enum type");
        return Enum.GetValues(t)
            .Cast<T>()
            .Select(x => new KeyValuePair<string, string>(
                ((int)Enum.ToObject(t, x)).ToString("00"), 
                Regex.Replace(x.ToString(), "([A-Z])", " $1").Trim()
                ));
    }

它给了我几乎相同的结果,但它缺少命名“Value”和“Text”。有人可以告诉我如何修改后面的代码来添加这些并仍然按顺序返回结果吗?

我自己尝试过这样做,但当我尝试将“Value =”和“Text =”添加到通用选项中时,它给了我错误:

错误6当前上下文中不存在名称“值”

1 个答案:

答案 0 :(得分:2)

您需要定义一个类,其值将返回:

public class YourValues
{
    public string Value {get; set;}
    public string Text {get; set;}
}

并修改如下:

public static IEnumerable<YourValues> GetValues2<T>() where T : struct 
{
    var t = typeof(T);
    if (!t.IsEnum)
        throw new ArgumentException("Not an enum type");
    return Enum.GetValues(t)
        .Cast<T>()
        .Select(x => new YourValues{
            Value = ((int)Enum.ToObject(t, x)).ToString("00"), 
            Text = Regex.Replace(x.ToString(), "([A-Z])", " $1").Trim()
            });
}