Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use LINQ with WorkItemCollection

Tags:

c#

linq

I am using the COM interface to TFS. (TeamFoundationServer.ExtendedClient v14.95.3). I am trying to use LINQ to iterate over the various collections. For example, this function works great:

    public static IEnumerable<string> GetTitles(WorkItemCollection workItemList)
    {
        return from WorkItem item in workItemList select item.Fields["Title"].Value.ToString();
    }

However, when I try to change to use the method syntax it fails:

    public static IEnumerable<string> GetTitles2(WorkItemCollection workItemList)
    {
        return workItemList.Select(item => item.Fields["Title"].Value.ToString());
    }

... gives me error "'WorkItemCollection' does not contain a definition for 'Select'..."

I have using System.Linq; in my file. And I am referencing System.Core.dll. The WorkItemCollection does implement IEnumerable. So why doesn't this work?

like image 460
John Henckel Avatar asked Dec 07 '22 21:12

John Henckel


2 Answers

WorkItemCollection does only implement IEnumerable, but not IEnumerable<WorkItem>. The LINQ extensions are declared only for IEnumerable<T>, not for the non-generic IEnumerable.

What you can do is use OfType<T>():

public static IEnumerable<string> GetTitles2(WorkItemCollection workItemList)
{
    return workItemList.OfType<WorkItem>()
                       .Select(item => item.Fields["Title"].Value.ToString());
}

Instead of OfType<T> you can also use Cast<T>. But if there is something other than a WorkItem in the sequence (which is probably never the case in this scenario), Cast<T> would throw an InvalidCastException while OfType<T> would ignore that element.

like image 168
René Vogt Avatar answered Dec 10 '22 10:12

René Vogt


WorkItemCollection implements IEnumerable, not IEnumerable<T>. It's the latter, generic, interface that is the foundation of LINQ.

You can convert from one to the other using the Cast<T> extension method, however:

workItemList.Cast<WorkItem>.Select(item => ...
like image 35
Charles Mager Avatar answered Dec 10 '22 10:12

Charles Mager