简体   繁体   English

ILIst的Linq表达式可在VB.Net中使用,但不能在C#中使用?

[英]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. 我当时正在转换一些代码,并使用Telerik的代码转换器,然后进行了临时更改,但遇到了让我有些困惑的事情。 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. 如果我想要一个通用的IList,可用于在WPF的从属属性中创建可能成为任何对象的IList的列表。 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? 但是,在C#中是否有语言解决方案可以使其正常工作?

The closer C# LINQ query syntax is to specify explicitly object as type of the range variable p . 更紧密的C#LINQ查询语法是将object明确指定为范围变量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): 此外,我不知道VB.NET,但在C# select需要(可以跳过只有当最后一个操作员group by W / O into条款):

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) 参考: 如何:使用LINQ(C#) 查询ArrayList与如何:使用LINQ(Array)查询ArrayList

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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