Friday, October 12, 2007

LINQ: Iterate through collection which implements IEnumerable only

The following works fine in LINQ, because an array implements IEnumerable <T>.

string[] tokenArray = new string[2] { "Hello", "World" }; 
var tokens = from token in tokenList select token;

foreach (var item in tokens)
Console.WriteLine(item);




But, the collections which do not implement IEnumerable<T> or IQueryable, can not be iterated in LINQ in the same way. To achieve the same, make use of a simple casting trick such as:




ArrayList tokenList = new ArrayList(); 
tokenList.Add("Hello");
tokenList.Add("World");

var tokens = from string token in tokenList select token;

foreach (var item in tokens)
Console.WriteLine(item);




1 comment:

Zubair.NET! said...

Or you can write

foreach (var item in tokens) Console.WriteLine(item.ToString());