Cast Object to Generic List

后端 未结 8 1200
野趣味
野趣味 2020-12-03 03:37

I have 3 generict type list.

List = new List();
List
= new List
(); List = new Lis
相关标签:
8条回答
  • 2020-12-03 03:59

    I had the same problem and solved it by looking at the purpose of the casted objects. Do you really need to cast it to the specific (closed) generic types? In my case the (open) generic type had an interface which I used to cast it to.

    var list = obj as IUsefulInterface;
    
    list.MethodThatIAmInterestedIn();
    
    0 讨论(0)
  • 2020-12-03 04:03

    Lots of trial and error gave me this on SL 5 but it should also work on a regular C#. You also need to add LINQ to your using list for the last half to work.

        List<object> myAnythingList = (value as IEnumerable<object>).Cast<object>().ToList()
    

    Enjoy!

    0 讨论(0)
  • 2020-12-03 04:06

    You might need to do:

    if(object is List)
    {
        list = (List)object
    }
    
    0 讨论(0)
  • 2020-12-03 04:09

    A general solution like this (to instantiate a type with a generic parameter based on a System.Type object) is not possible. If you're really just dealing with these three types, though, then you're in luck because it's pretty easy:

    Type t = typeof(obj);
    
    if (t == typeof(List<Contact>)) {
        var contactList = (List<Contact>)obj;
        // do stuff with contactList
    
    } else if (t == typeof(List<Address>)) {
        var addressList = (List<Address>)obj;
        // do stuff with addressList
    
    } else if (t == typeof(List<Document>)) {
        var documentList = (List<Document>)obj;
        // do stuff with documentList
    }
    
    0 讨论(0)
  • 2020-12-03 04:11

    I ran into same problem - I have a collection which data type is only known at run time and I can't cast it to anything. None of the solutions above worked. Finally I solved it by serializing to JSON and de-serializing back. Of course it's not ideal, but may help someone.

    string jsonString = JsonConvert.SerializeObject(myObject);
    jsonString = "{ values:" + jsonString + "}";
    
    JObject j = JObject.Parse(jsonString);
    
    //now we can iterate over the list
    foreach (var x in j["values"])
    {
        string name = x.ToString();
        ...
    }
    
    0 讨论(0)
  • 2020-12-03 04:14

    I had this problem when writing a Validation Attribute where I received an object from the ValidationContext and knew that it needed to be a list, but not what it was a list of. It threw an exception when I tried to cast it as IEnumerable<object> but it could be cast as IEnumerable which then allowed the .Cast<object>() via linq.

    In the end what worked was:

    var enumerable = listObject as IEnumerable;
    var list = enumerable.Cast<object>().ToList();
    
    0 讨论(0)
提交回复
热议问题