0

I want to pass in an unknown object to a method, and then let it return the object as a List. Basically, I want something like this

object b = new MyType();
object a = new List<MyType>()

public List<object> convertObjectBackToList(object Input)
{
    //if Input is an IList type (Ex: object a above)
    //return List<object>;

    //if Input is an generic object type. (Ex: object b above)
    //return an List<object> which has only one object.
    List<object> Output = new List<object>();
    Output.Add(Input);
    return Output;
}

You can cast your object first to IEnumerable, then convert to list.

public List<object> convertObjectBackToList(object Input)
{
    if(Input is IEnumerable)
        return ((IEnumerable)Input).Cast<Object>().ToList();
    return new List<Object>() { Input };
}

EDIT

A generic extension method would even be better

public static partial class SOExtensions
{
    public static List<T> ToList2<T>(this object Input)
    {
        if (Input is IEnumerable)
            return ((IEnumerable)Input).Cast<T>().ToList();
        return new List<T>() { (T)Input };
    }
}

Then you could use it as

var list1 = someObject.ToList2<SomeType>();
4

1 回答 1

6

您可以先将对象IEnumerable转换为 ,然后转换为列表。

public List<object> convertObjectBackToList(object Input)
{
    if(Input is IEnumerable)
        return ((IEnumerable)Input).Cast<Object>().ToList();
    return new List<Object>() { Input };
}

编辑

一个通用的扩展方法会更好

public static partial class SOExtensions
{
    public static List<T> ToList2<T>(this object Input)
    {
        if (Input is IEnumerable)
            return ((IEnumerable)Input).Cast<T>().ToList();
        return new List<T>() { (T)Input };
    }
}

然后你可以用它作为

var list1 = someObject.ToList2<SomeType>();
于 2013-10-05T18:24:27.350 回答