简体   繁体   English

我如何使用LINQ来“修剪”字典?

[英]How can I use LINQ to “prune” a dictionary?

I have a Dictionary and a List of keys to remove from the dictionary. 我有一个词典和要从词典中删除的键列表。 This is my implementation right now: 这是我现在的实现:

var keys = (from entry in etimes
            where Convert.ToInt64(entry.Value) < Convert.ToInt64(stime)
            select entry.Key).ToList();

foreach (var key in keys)
{
    etimes.Remove(key);
    count--;
}

Is there something I can do the eliminate the foreach loop? 我有什么办法可以消除foreach循环吗?

var pruned = etimes.Where(entry => Convert.ToInt64(entry.Value) >= 
    Convert.ToInt64(stime)).ToDictionary(entry => entry.Key, 
        entry => entry.Value);

This statement simply filters the dictionary using the LINQ Where function to select which items to keep rather than those to remove (which then requires further code, as you showed). 该语句仅使用LINQ Where函数过滤字典,以选择要保留的项,而不是要删除的项(然后,您需要显示进一步的代码)。 The ToDictionary converts thwe IEnumerable<KeyValuePair<TKey, TValue>> to the desire Dictionary<TKey, TValue> type, and is at least quite simple, if not terribly elegant or efficient due to the need to specify the two lambda expressions to select the key and value from a KeyValuePair (and then creating a new dictionary). ToDictionaryIEnumerable<KeyValuePair<TKey, TValue>>为所需的Dictionary<TKey, TValue>类型,并且由于需要指定两个lambda表达式来选择,所以至少相当简单(如果不是非常优雅或高效)。 KeyValuePair键和值(然后创建一个新字典)。 Saying this, I don't really see it as a problem, especially if the dictionary is small and/or number of items being removed is large. 这样说,我并不认为这确实是一个问题,尤其是当字典很小和/或要删除的项目数量很大时。

Well, performance or readability issues aside, couldn't this also be done something like the following: 好吧,除了性能或可读性问题外,还不能通过以下方式完成此操作:

<Extension> void itemDelete(List l, object item) {
    l.Remove(item)
}

var keys = (from entry in etimes
        where Convert.ToInt64(entry.Value) < Convert.ToInt64(stime)
        select entry.Key).ToList();

keys.foreach(itemDelete());

Forgive my coding, I'm not 100% certain of the exact syntax (especially in C#); 原谅我的编码,我不确定100%的确切语法(尤其是在C#中); consider that pseudo-code. 考虑一下伪代码。 Note the addition of the new function, and the .foreach function on the end of the LINQ query. 请注意新功能的添加,以及LINQ查询末尾的.foreach函数。 I know this would be possible in VB, i assume C# has something similar... if not you could always write your own .foreach extension. 我知道这在VB中是有可能的,我认为C#具有类似的功能……否则,您始终可以编写自己的.foreach扩展名。 It may or may not improve anything, but it's an idea. 它可能不会有所改善,但这是一个主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM