Linq查询删除值为>的第一个条目字典中的0,当所有后续值都为零时

时间:2013-04-02 05:43:09

标签: linq dictionary

这是字典,

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且后续值为零时,删除第一个键,否则不执行任何操作。

2 个答案:

答案 0 :(得分: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);
}

答案 1 :(得分:0)

在此之后使用条件stmt查看LINQ。如果删除OrNot为true,则可以删除第一个项目。删除不能在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);