簡體   English   中英

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

[英]How can I add in field naming to a KeyValuePair in 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 =”添加到泛型的選擇中時,它給了我錯誤:

錯誤6當前上下文中不存在名稱“值”

您需要定義一個類,其值將返回:

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()
            });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM