【问题标题】:return objects of a specific type in linq query在 linq 查询中返回特定类型的对象
【发布时间】:2013-04-23 16:41:40
【问题描述】:

我正在尝试编写一个返回特定类型的所有对象的 linq 查询。

如果我想得到所有轿车的车,这样的事情会起作用吗?

Dim cars = From c In carFactory.GetAllcars()
           Select car = carFactory.GetAuto(c.ID)
           Where TypeOf (car) Is Sedan

【问题讨论】:

  • 如果你执行 getAllcars() ,你有一个奇怪的模型,它返回一个类型,你必须在同一个工厂调用 GetAuto 来获取汽车对象。

标签: .net vb.net linq


【解决方案1】:

这可行,但返回类型仍为IEnumerable(Of Car)

相反,您可以写sequence.OfType(Of Sedan)();这将过滤掉非轿车返回IEnumerable(Of Sedan)

【讨论】:

  • @999cm999: sequence 是任何 IEnumerable 或 LINQ 查询。
【解决方案2】:
 carFactory.GetAllcars().OfType<Sedan>().Select(car=>car.ID)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-21
    • 2012-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多