Search code examples
c#arraylistextension-methods

How can I make an extension for a list of lists


I want to make an extension for a list of lists, if possible. I've tried variations on this theme, but none worked:

public static List<List<myClass>> ToListsOfmyClass(this IEnumerable<IEnumerable<OtherClass>> listsOfOtherClass)
{
    return listsOfOtherClass.SelectMany(many => many.Select(p => new myClass(p)).ToList()).ToList();
}

I receive the following compile error:

Error CS0029 Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.List>' SSX.Revit.Access D:\SourceCode\WorkSpaces\AllProjects\SSX.Revit\r2020 (v.20)\Startup (plugin)\v1.0\SSX.Revit.Access\Support\AIMPoint.cs 67 Active


Solution

  • Note that the myClass(p) works fine as I use it elsewhere.

    This fact is completely irrelevant to the actual problem, the error message should be along the lines of:

    Cannot implicitly convert type 'System.Collections.Generic.List<T>' to 'System.Collections.Generic.List<System.Collections.Generic.List<T>>'
    

    As we said in comments you could modify your method to return List<List<T>>:

    public static List<List<myClass>> ToListsOfmyClass(this IEnumerable<IEnumerable<OtherClass>> listsOfOtherClass)
    {
        return listsOfOtherClass.Select(x => x.Select(p => new myClass(p)).ToList()).ToList();
    }
    

    Or add another method where we flatten the collection and return List<T>:

    public static List<myClass> ToFlattenedListsOfmyClass(this IEnumerable<IEnumerable<OtherClass>> listsOfOtherClass)
    {
       return listsOfOtherClass.SelectMany(x => new myClass(p)).ToList();
    }
    

    As an aside, in number of scenarios, where for example we have 1000 classes like this I'd consider adding a generic method or using a tool like AutoMapper. For example:

    public static List<List<To>> ToListsOfmyClass<From>(this IEnumerable<IEnumerable<From>> listsOfOtherClass) where From : IMyConvertible
    {
       return listsOfOtherClass.Select(x => x.Select(p => p.Convert<To>()).ToList()).ToList();
    }
    
    interface IMyConvertible { ... }
    

    This would require From to implement method .Convert from interface IMyConvertible