如何同时使用LINQ返回匿名类型 [英] How to return Anonymous Type while using Linq

查看:204
本文介绍了如何同时使用LINQ返回匿名类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:结果
LINQ to SQL的:返回匿名类型






做任何一个知道如何返回一个匿名类型。我使用LINQ,我需要返回下面的代码



 私营<什么是在这里与GT提供的返回类型; SampleLinq(的Int32 NUM)
{
VAR的查询=(从obj.DeptTable部门那里dept.Id ==民选择新的{dept.DeptName,dept.DeptId});
回报(查询)

}


解决方案

遗憾地说,但你不能返回匿名类型出方法的范围。



这是另一种方式来获得anonmous类型

  //方法返回匿名类型的对象
对象ReturnAnonymous()
{
返回新{市=布拉格,名称=托马斯};
}

//应用程序的入口点
无效的主要()
{
//获取匿名类型的实例与城市和名称物业
对象o = ReturnAnonymous();

//这个调用投射方法转换第一个参数(对象)到
//同类型的第二个参数的类型 - 这是在这种情况下,
/ /匿名类型与城市和名称的属性
变种类型= CAST(0,新{市=,名称=});
Console.WriteLine(NAME = {0},市= {1},typed.Name,typed.City);
}

//铸造方法 - 由于调用方法时,类型推断它
//可以投对象键入不知道类型名$ B $(B T)演员LT ; T>(obj对象,T型)
{
回报率(T)OBJ;
}

您可以用它只能在一个程序集中的类型(两个匿名类型从两个不同的组件将在内部编译为两个不同的类型,而且不能使用此招)进行转换。


Possible Duplicate:
LINQ to SQL: Return anonymous type?

Do any one know how to return an anonymous type. I am using Linq where i need to return the following code

private <What's the return type to be provided here> SampleLinq(Int32 Num)
    {
        var query = (from dept in obj.DeptTable where dept.Id == Num select new { dept.DeptName, dept.DeptId });
        return (query)       

    }

解决方案

Sorry to say but you cannot return anonymous type out side the scope of method.

This is the alternate way to get anonmous type

// Method that returns anonymous type as object
object ReturnAnonymous()
{
  return new { City="Prague", Name="Tomas" };
}

// Application entry-point
void Main()
{
  // Get instance of anonymous type with 'City' and 'Name' properties
  object o = ReturnAnonymous();

  // This call to 'Cast' method converts first parameter (object) to the
  // same type as the type of second parameter - which is in this case 
  // anonymous type with 'City' and 'Name' properties
  var typed = Cast(o, new { City="", Name="" });
  Console.WriteLine("Name={0}, City={1}", typed.Name, typed.City);
}

// Cast method - thanks to type inference when calling methods it 
// is possible to cast object to type without knowing the type name
T Cast<T>(object obj, T type)
{
  return (T)obj;
}

you can use it only for types in one assembly (two anonymous types from two different assemblies will be internally compiled to two different types that can't be converted using this trick).

这篇关于如何同时使用LINQ返回匿名类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆