djangojazz
djangojazz

Reputation: 13272

Linq expression for ILIst works in VB.Net but not C#?

I was converting some code and using Telerik's Code Converter and then ad hoc changing but came across something that stumped me a little bit. I want to keep it as close as possible to what it was but am curious best way. It appears

If I want a generic IList, to use for making Lists in a Dependent Property in WPF that could become and IList of any object. I can mock it up in a console app like this:

WORKS:

Private _listTest As IList

Public Property ListTest As IList
  Get
    Return _listTest
  End Get
  Set(ByVal value As IList)
    _listTest = value
  End Set
End Property

Sub Main()
  ListTest = New List(Of Integer)({1, 2, 3, 4})
  Dim items = From p In ListTest
End Sub

DOES NOT WORK:

private static IList _listTest;

public static IList ListTest
{
  get { return _listTest; }
  set { _listTest = value; }
}

static void Main(string[] args)
{
  ListTest = new List<int> { 1, 2, 3, 4 };
  //Error:Could not find an implementation of the query pattern for source type 'IList'.  'Select' not found.  Consider explicitly specifying the type of the range variable 'p'.
  var items = from p in ListTest;
}

The problem with the listing saying the equivalent of being explicit, is this will be done for a generic. I suppose I could do a listing of object. But is there a language solution in C# to make it work?

Upvotes: 2

Views: 832

Answers (2)

Abdullah Dibas
Abdullah Dibas

Reputation: 1507

You should either consider to make your list of generic type IList<object> or every time you try to use Linq methods with your list you should use .OfType<T> or .Cast<T>.

var items = from p in ListTest.Cast<object>() select p;

Upvotes: 0

Ivan Stoev
Ivan Stoev

Reputation: 205749

The closer C# LINQ query syntax is to specify explicitly object as type of the range variable p. Also I don't know about VB.NET, but in C# select is required (can be skipped only if the last operator is group by w/o into clause):

var items = from object p in ListTest select p;

Reference: How to: Query an ArrayList with LINQ (C#) vs How to: Query an ArrayList with LINQ (Visual Basic)

Upvotes: 4

Related Questions