簡體   English   中英

刪除字典中的最后n個元素

[英]c# - Remove last n elements from Dictionary

如何從字符串字典中刪除最后2個keyValuePairs,其中字符串以“ MyKey_”開頭?

var myDict = new Dictionary<string, string>();    

myDict.Add("SomeKey1", "SomeValue");
myDict.Add("SomeKey2", "SomeValue");
myDict.Add("MyKey_" + Guid.NewGuid(), "SomeValue");
myDict.Add("MyKey_" + Guid.NewGuid(), "SomeValue");
myDict.Add("MyKey_" + Guid.NewGuid(), "SomeValue");

編輯:

var noGwInternal = myDict.Where(o => !o.Key.StartsWith("MyKey_")).ToDictionary(o => o.Key, o => o.Value);
var gwInternal = myDict.Where(o => o.Key.StartsWith("MyKey_")).ToDictionary(o => o.Key, o => o.Value);

如何從這里前進? 需要從gwInternal中刪除2個項,然后將noGwInternal + gwInternal放到一個新的Dictionary中

這應該做您想做的事情(根據您在評論中發布的內容)。

(編輯:您似乎替換了您的評論,現在我不確定您要按字母順序...)

var myDict = new Dictionary<string, string>();    

myDict.Add("SomeKey1", "SomeValue");
myDict.Add("SomeKey2", "SomeValue");
myDict.Add("MyKey_B" + Guid.NewGuid(), "SomeValue");
myDict.Add("MyKey_A" + Guid.NewGuid(), "SomeValue");
myDict.Add("MyKey_C" + Guid.NewGuid(), "SomeValue");

var pairsToRemove = myDict.Where(x => x.Key.StartsWith("MyKey_"))
                          .OrderByDescending(x => x.Key)
                          .Take(2);

foreach (var pair in pairsToRemove)
{
    myDict.Remove(pair.Key);
}

foreach (var pair in myDict)
{
    Console.WriteLine(pair);
}

輸出:( 已刪除MyKey_B和MyKey_C)

[SomeKey1, SomeValue]
[SomeKey2, SomeValue]
[MyKey_Ad6c3a25d-5d8c-44e4-9651-39164c0496fc, SomeValue]

我喜歡tevemadar關於OrderedDictionary提到的內容...我不確定它是否可以用於您要嘗試的操作,但是值得一看。

由於這是一本字典(沒有順序),因此不確定您的意思是“ last”,但是此代碼將按照在循環中遇到的順序刪除后2個字符。

List<string> toRemove = new List<string>();  
foreach(KeyValuePair pair in myDict.Reverse())
{
     if(pair.key.StartsWith("MyKey_"))
     {
           toRemove.Add(pair.key);
           toRemoveCount--;
     }

     if(toRemove.Count == 2)
     {
           break;
     }
}

foreach(string str in toRemove)
{
      myDict.Remove(str);
}

暫無
暫無

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

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