简体   繁体   中英

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?

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)

您应该考虑制作通用类型IList<object>列表,或者每次尝试在列表中使用Linq方法时,都应使用.OfType<T>.Cast<T>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM