簡體   English   中英

C#制作了Lambda的字典

[英]C# make a Dictionary of Lambdas

我在定義字典以快速訪問Lambda表達式時遇到了麻煩。

我們假設我們有一個這樣的知名類:

class Example
{
    public string Thing1;
    public DateTime Thing2;
    public int Thing3;
}

想要做的是這樣的事情:

var getters = new Dictionary<string, IDontKnowWhatGoesHere>();
getters.Add("Thing1", x => x.Thing1);
getters.Add("Thing3", x => x.Thing3);

這可能嗎?

編輯:

這是我對這個對象的用例:

List<Example> array = new List<Example>();

// We actually get this variable set by the user
string sortField = "Thing2";

array.Sort(getters[sortField]);

非常感謝您的幫助。

你有幾個選擇。 如果在您的示例中,您想要獲取的內容都是相同類型(即String ),則可以執行此操作

var getters = new Dictionary<string, Func<Example, String>>();

但是,如果它們是不同的類型,則需要使用最低的公共子類,在大多數情況下它們將是Object

var getters = new Dictionary<string, Func<Example, object>>();

請注意,您需要將返回值強制轉換為預期類型。

嘗試:

var getters = new Dictionary<string, Func<Example, object>>();
getters.Add("Thing1", x => x.Thing1);
getters.Add("Thing3", x => x.Thing3);

Func委托的第一個泛型類型參數是輸入的類型,第二個泛型類型參數是輸出的類型(使用object因為您有不同的輸出類型)。 更多關於FuncFunc<T, TResult> Delegate

var getters = new Dictionary<string, Expression<Func<Example, object>>>();

但是, string Thing1應該是公開的。

我真的認為你是以錯誤的方式思考這個問題。 為什么要使用字典呢? 如果您的類定義正確,那么只需使用List<Example>

List<Example> dataList = new List<Example>();
dataList.Add(new Example { Thing1 = "asdf", Thing2 = "qwert", Thing3 = 2 });

然后你就可以使用linq了。

IEnumerable<Example> sortedByT3 = dataList.OrderBy(x => x.Thing3);

sortedByT3.Last().Thing2 = "hjkl";

您還可以使用Marc Gravell提供的dynamic order by

var sortedByString = dataList.AsQueryable().OrderBy("Thing2");

不需要lambdas,只需直接訪問數據即可。

正如大家所說,你需要讓成員公開。 我建議你把它改成以下內容:

public class Example
{
    public string Thing1 { get; set; }
    public string Thing2 { get; set; }
    public int Thing3 { get; set; }
}

暫無
暫無

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

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