简体   繁体   中英

C# Conversion from List<List<int>> to IList<IList<int>>

I have a C# function like this-

public IList<IList<int>> Subsets(int[] nums)
{
    List<List<int>> output = new List<List<int>>();
    if (nums.Length == 0)
    {
        return output;    //Problem in this line
        //return null;
    }
    ........
    ........
    return output.Concat(Subsets(nums.Skip(1).ToArray())).ToList();
}

What I am finding is-

Severity    Code    Description Project File    Line    Suppression State

Error   CS0266
Cannot implicitly convert type 'System.Collections.Generic.List<System.Collections.Generic.List<int>>' to 'System.Collections.Generic.IList<System.Collections.Generic.IList<int>>'.

An explicit conversion exists (are you missing a cast?) LeetCode    D:\LeetCode\Solution.cs 13  Active

错误

Can anyone please help?

Try this:

IList<IList<int>> list2 = list.Cast<IList<int>>().ToList();

You have to add using System.Linq; for that.

Change

List<List<int>> output = new List<List<int>>();

to

List<IList<int>> output = new List<IList<int>>();

You can cast the outer list to IList, since List implements IList, but you can't force the cast of the type argument of List, so it should be declared as IList since the beginning.

Thanks to @NetMage for the great comment.

I have changed

return new List<List<int>>();

to

return new List<IList<int>>();

Which works great for me.

Though, I agree with other answers to create appropriate interface, you can do this without creating new list like Gur Galler proposed with a little bit of hardcore hacking:

[StructLayout(LayoutKind.Explicit)]
public struct Union
{
    [FieldOffset(0)]
    public List<List<int>> a;
    [FieldOffset(0)]
    public IList<IList<int>> b;

    public static IList<IList<int>> Cast(List<List<int>> list)
    {
        var u = new Union();
        u.a = list;
        return u.b;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var lists = new List<List<int>>() { new List<int>() { 1, 2, 3 } };
        IList<IList<int>> casted = Union.Cast(lists);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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