我不太清楚你想在這裏實現什麼,所以也許我的答案不是你要找的。
無論如何,在通用列表中,您可以在集合上使用lambda表達式/ linq語句。考慮我寫給你們的這些例子:
internal class ListLambdaLINQSample
{
List<KeyValuePair<Colors, int>> listSource;
List<KeyValuePair<Colors, int>> listCriteria;
List<KeyValuePair<Colors, int>> listMatches;
private const int COLORCODE1 = 1;
private const int COLORCODE2 = 2;
private const int COLORCODE3 = 3;
private const int COLORCODE4 = 4;
private const int COLORCODE5 = 5;
internal enum Colors
{
Red, Blue, Green, Yellow
}
public ListLambdaLINQSample()
{ // populate the list
listSource = new List<KeyValuePair<Colors, int>>();
listCriteria = new List<KeyValuePair<Colors, int>>();
_populateListCriteria();
_populateListSource();
...
}
private void _getMatchesWithLINQ()
{
listMatches =
(from kvpInList
in listSource
where !listCriteria.Contains(kvpInList)
select kvpInList).ToList();
}
private void _getMatchesWithLambda()
{
listMatches =
listSource.Where(kvpInList => !listCriteria.Contains(kvpInList)).ToList();
}
private void _populateListSource()
{
listSource.Add(new KeyValuePair<Colors, int>(Colors.Blue, COLORCODE1));
listSource.Add(new KeyValuePair<Colors, int>(Colors.Green, COLORCODE2));
listSource.Add(new KeyValuePair<Colors, int>(Colors.Red, COLORCODE3));
listSource.Add(new KeyValuePair<Colors, int>(Colors.Yellow, COLORCODE4));
}
private void _populateListCriteria()
{
listCriteria.Add(new KeyValuePair<Colors, int>(Colors.Blue, COLORCODE1));
listCriteria.Add(new KeyValuePair<Colors, int>(Colors.Green, COLORCODE2));
}
}
希望這有助於!
問候, 尼科
PS:我沒有編制,也沒有測試此代碼。
oops:您在過濾的列表上使用索引?這將返回0,1,2(測試它) – sehe
這將使用語句criteriaList.Contains(x)一次搜索整個criteriaList?它會返回colorList的索引整數值嗎? – KerryL
@sehe,@KerryL:哎呀!現在修復它。 – LukeH