开发者

Identifying whether an object is a type of List and iterating over it

开发者 https://www.devze.com 2022-12-21 05:33 出处:网络
I am trying to determine if an object x is a list. It may be a list of any type and with any generic p开发者_开发问答arameter.

I am trying to determine if an object x is a list. It may be a list of any type and with any generic p开发者_开发问答arameter.

If it is, then I want to iterate over it if it is. This is the best I could come up with, but it fails due to a compilation error

if(x is List){
    foreach(Object o in (List)x){
        ;
    }
}

How can I do this?


The easiest way is to cast to IList. This is a non-generic interface and could be implemented by non-generic lists (such as ArrayList) but I'm guessing that won't be a concern for you:

if (x is IList) {
  foreach (object o in (IList)x) {
    // ...
  }
}

(And if all you need to do is foreach, you don't even need IList: IEnumerable will suffice.)

Note that the non-generic IList and IEnumerable are in the System.Collections namespace, which is not using-ed by default. So you will need to add using System.Collections; (thanks to Reed Copsey for noting this).


You can use "as" to save a cast:

var xList = x as IList;
if(x != null) {
    foreach(object o in xList){
      // ...
    }
}


if (x.GetType().IsInstanceOfType(typeof(IList<string>)))
{
  foreach (Object o in x) // replace with you type
  { }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号