Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if IEnumerable<object> is IEnumerable<int>

Tags:

c#

linq

I've IEnumerable<object> type variable.

IEnumerable<object> items= new object[] { 1, 2, 3 };

What's the best way to check if it's IEnumerable<int>?

I tried

typeof(IEnumerable<int>).IsAssignableFrom(items.GetType())
typeof(IEnumerable<int>).IsInstanceOfType(items)
items is IEnumerable<int>

But, Re-Sharper complains about them all.

In my case, IEnumerable<object> items is of type IEnumerable<int> in most cases. And I wanted to carry out something when it's of type IEnumerable<int> and something else for other types.

like image 724
ANewGuyInTown Avatar asked May 27 '15 06:05

ANewGuyInTown


1 Answers

If you want to check if an IEnumerable<object> contains only ints, you can use Enumerable.All:

var isInts = items.All(x => x is int);
like image 75
Yuval Itzchakov Avatar answered Oct 03 '22 03:10

Yuval Itzchakov