LINQ:比较两个列表并计数子集 [英] LINQ: Compare two lists and count subset

查看:119
本文介绍了LINQ:比较两个列表并计数子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在比较2个列表,并且仅当发现一个以上事件时,才需要从主列表(allModules)中收集一个子集(modulesToDelete)的出现. (allModules包含modulesToDelete). modulesToDelete中任何模块的多次出现表示这些模块正在共享.如果在modulesToDelete中出现一个模块,则表示该模块是隔离的,可以安全删除(它本身才发现).我可以使用嵌套的foreach循环来做到这一点,但这与我使用LINQ表达式(不起作用)收集到的一样:

I am comparing 2 lists and I need to collect occurrences of a subset (modulesToDelete) from the master list (allModules) ONLY when MORE than one occurrence is found. (allModules contains modulesToDelete). Multiple occurrences of any module in modulesToDelete means those modules are being shared. One occurrence of a module in modulesToDelete means that module is isolated and is safe to delete (it just found itself). I can do this with nested foreach loops but this is as far as I got with a LINQ expression (which doesn't work)collect:

List<Module> modulesToDelete = { A, B, C, K }
List<string> allModules = {R, A, B, C, K, D, G, T, B, K }  // need to flag B and K

var mods = from mod in modulesToDelete
where allModules.Any(name => name.Contains(mod.Name) && mod.Name.Count() > 1)
select mod;

这是我想用LINQ表达式替换的嵌套的foreach循环:

here is my nested foreach loops which I want to replace with a LINQ expression:

foreach (Module mod in modulesToDelete)
{
    int count = 0;
    foreach (string modInAllMods in allModules)
    {
        if (modInAllMods == mod.Name)
        {
            count++;
        }
    }

    if (count > 1)
    {
        m_moduleMarkedForKeep.Add(mod);
    }
    else if( count == 1)
    {
        // Delete the linked modules
    }
}

推荐答案

您可以使用类似于字典的查找,但是允许多个相等的键并返回IEnumerable<T>作为值.

You can use a lookup which is similar to a dictionary but allows multiple equal keys and returns an IEnumerable<T> as value.

var nameLookup = modulesToDelete.ToLookup(m => m.Name);
var safeToDelete = modulesToDelete.Where(m => nameLookup[m.Name].Count() == 1);
var sharedModules = modulesToDelete.Where(m => nameLookup[m.Name].Count() > 1);

但是,我完全不了解allModules的关系.

However, i don't see how allModules is related at all.

可能更容易,并在您的样本数据上获得了预期的结果:

Probably easier and with the desired result on your sample data:

var mods = modulesToDelete.Where(m => allModules.Count(s => s == m.Name) > 1);

这篇关于LINQ:比较两个列表并计数子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆