LINQ: Compare two lists and count subset

喜欢而已 提交于 2019-12-12 01:53:38

问题


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;

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
    }
}

回答1:


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);

Edit: 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);



回答2:


One way of going about solving this will be to use Intersect function, Intersection of two string array (ignore case)



来源:https://stackoverflow.com/questions/28301074/linq-compare-two-lists-and-count-subset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!