C# Is Type in list question
Basic c# question. In the sample bellow But the 'is' doesn't like the type variable. Any ideas there should be a simple answer.
List<object> list = new List<object>();
list.Add("one");
list.Add(2);
list.Add('3');
Type desiredType = typeof(System.Int32);
if 开发者_JAVA技巧(list.Any(w => w is desiredType))
{
//do something
}
Try this:
List<object> list = new List<object>();
list.Add("one");
list.Add(2);
list.Add('3');
Type desiredType = typeof(System.Int32);
if (list.Any(w => w.GetType().IsAssignableFrom(desiredType)))
{
//do something
}
Anyway: are you sure you want to create a list of objects?
w.GetType() == desiredType
.
Why are you abusing generics like that?
You could use the Linq extension method OfType:
list.OfType<> will return an IEnumerable to any items of the specified type.
If I recall correctly you have to write w is System.Int32
..
The delegate is expecting a type or a namespace, but you're supplying a type instance. Try this:
if (list.Any(w => w is Int32))
{
//do something
}
精彩评论