0

这是字典,

Dictionary<string, uint> oSomeDictionary = new Dictionary<string, uint>();

oSomeDictionary.Add("Interface1",3);
oSomeDictionary.Add("Interface2",0);
oSomeDictionary.Add("Interface3",0);
oSomeDictionary.Add("Interface4",0);
oSomeDictionary.Add("Interface5",0);
oSomeDictionary.Add("Interface6",0);
oSomeDictionary.Add("Interface7",0);

条件:当第一个键的值oSomeDictionary大于0并且后面的值都为零时,如上,删除第一个键,否则什么都不做。

4

2 回答 2

1

有一个简单的代码可以解决您的需求,但您应该按照评论中的说明首先订购您的字典。请谨慎使用此代码。

Dictionary<string, uint> oSomeDictionary = new Dictionary<string, uint>();
oSomeDictionary.Add("Interface1", 3);
oSomeDictionary.Add("Interface2", 0);
oSomeDictionary.Add("Interface3", 0);
oSomeDictionary.Add("Interface4", 0);
oSomeDictionary.Add("Interface5", 0);
oSomeDictionary.Add("Interface6", 0);
oSomeDictionary.Add("Interface7", 0);

var ordered = oSomeDictionary.OrderBy(_ => _.Key);
if (ordered.First().Value > 0 && ordered.Skip(1).All(_ => _.Value == 0))
{
    oSomeDictionary.Remove(ordered.First().Key);
}
于 2013-04-02T09:10:11.720 回答
0

之后请参阅带有代码 stmt 的 LINQ。如果 deleteOrNot 为真,您可以删除第一项。无法在 LINQ 中完成删除。:)

      Dictionary<string, uint> oSomeDictionary = new Dictionary<string, uint>();

        oSomeDictionary.Add("Interface1", 3);
        oSomeDictionary.Add("Interface2", 0);
        oSomeDictionary.Add("Interface3", 0);
        oSomeDictionary.Add("Interface4", 0);
        oSomeDictionary.Add("Interface5", 0);
        oSomeDictionary.Add("Interface6", 0);
        oSomeDictionary.Add("Interface7", 0);
        bool deleteOrNot = ((from test1 in oSomeDictionary
                    where test1.Value > 0
                    select test1).Count() == 1) && (oSomeDictionary.First().Value > 0);
于 2013-04-02T06:30:12.290 回答