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);








Write a Comment

Note: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>