我想寫一個方法,該方法應該根據索引值和條件來回傳專案值。
例如,在下面,如果我傳遞索引值為0,它應該回傳鍵和整數陣列中的第一個值,這個值不是5。
public static Dictionary< string, int[]> _dict = new Dictionary< string, int[]> ()
{
{"A", [1,0, 3] },
{"B", [5,1,5] },
{"C", [7,11,5] },
{"D", [0,1,5] },
{"E", [14,0,5] },
{"F", [5,1,5] }
};
預期的O/P:
如果我傳遞索引值0,并且條件是 !=5,那么O/P應該是
{
{"A"/span>, 1 },
{"C", 7 },
{"D", 0 },
{"E", 14}, {"E", 14}.
};
uj5u.com熱心網友回復:
你可以通過兩個步驟實作這個目標:
5開頭的專案var res = _dict.Where(a => a.Value[0] !=5) 。
- 然后用剩下的鍵和它們的整數陣列中的第一個條目填充一個新的Dictionary 。
foreach(KeyValuePair< string,int[]> keyValuePair in res)
{
result.Add(keyValuePair.Key, keyValuePair.Value[0]) 。
}
完整的代碼將看起來像這樣
public static Dictionary< string, int[]> _dict = new Dictionary< string, int[]> ()
{
{"A", new int[] {1, 0,3 } },
{"B", new int[] {5, 1,5}。},
{"C", new int[] {7, 11,5}。},
{"D", new int[] {0, 1,5}}。
{"E", new int[] {14, 0,5}。},
{"F", new int[] {5, 1,5}。}
};
static Dictionary<string, int> GetResult(int valueIndex, Func< KeyValuePair<string, int[]>, bool> predicate)
{
Dictionary<string, int> result = new Dictionary<string, int>()。
var res = _dict.Where(predicate)。
foreach(KeyValuePair<string,int[]> keyValuePair inres)
{
result.Add(keyValuePair.Key, keyValuePair.Value[valueIndex])。
}
return result。
}
GetResult(valueIndex: 0, predicate: a => a.Value[0] != 5) 然后給出你想要的結果
{
{"A"/span>, 1 },
{"C", 7 },
{"D", 0 },
{"E", 14}, {"E", 14}.
};
uj5u.com熱心網友回復:
單行使用LINQ
var result = _dict.Where(x => x.Value[0] !=5)
.ToDictionary(x => x.Key, y => y.Value[0]) 。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/334241.html
標籤:
上一篇:基于條件的付款計劃
下一篇:迭代前清除Array的最佳地點?
