如何使用对象而不是匿名类型

时间:2017-04-25 08:54:18

标签: c# linq

我有这些LINQ查询:

        var type1 = (from ftr in db.TB_FTR
                              join mst in db.TB_MST on ftr.MST_ID equals mst.MST_ID
                              join trf in db.TYPE_ID on mst.TYPE_ID equals trf.ID
                              where ftr.CITY == city && ftr.COUNTY == county
                              select new MyType { City = ftr.CITY, County = ftr.COUNTY Type = trf.TYPE }
              ).OrderBy(i => i.City);

        var type2 = type1.GroupBy(i => new { i.City, i.County, i.Type })
            .Select(group => new { Name = group.Key, MyCount = group.Count() })
            .OrderBy(x => x.Name).ThenByDescending(x => x.MyCount)
            .GroupBy(g => new { g.Name.City, g.Name.County })
            .Select(g => g.Select(g2 =>
            new { Name = new  { g.Key.City, g.Key.County, g2.Name.Type }, g2.MyCount })).Take(1000).ToList();

如您所见,第二个查询返回匿名类型。但我想在方法中使用这些查询。所以我不能返回匿名类型。如何将type2设为非匿名类型?

我为此准备了两个对象:

public class MyType
{
        public string City { get; set; }
        public string County { get; set; }
        public string Type { get; set; }
}

public class ProcessedType 
{
public MyType Name {get; set;}
public int MyCount {get; set;}
}

但我无法正确使用它们,因为我可能在查询中放错了它们。你可以帮助我,以便我可以让第二个查询返回一个已定义的对象吗?感谢。

3 个答案:

答案 0 :(得分:1)

你的代码中有这个:

for (i in 1:length(list_of_nested_node_names )) {
  position_in_list <- paste(position_in_list, "[[\"", list_of_nested_node_names[i], "\"]]", sep = "")
  eval(parse(text = paste(position_in_list, "<- list(1)")))
}

哪些仍然是匿名类型。您必须在其中放置实际的类型名称才能返回它们:

new { Name = new  { g.Key.City, g.Key.County, g2.Name.Type }, g2.MyCount }

查看代码,您还应该能够分配现有的new ProcessedType { Name = new MyType { g.Key.City, g.Key.County, g2.Name.Type }, g2.MyCount }

Name

答案 1 :(得分:1)

每当您编写new 而非后跟类型名称时,您都会创建一个anoynmous类型的实例。正如您所知,您无法将这些实例传递给其他方法(有效地,可以,因为即使是匿名类型也会从System.Object继承,但这样您就会丢失所有类型信息实际类型)。

在您的情况下,您已经拥有命名类型 - ProcessedType。所以不要这样:

new { Name = new  { g.Key.City, g.Key.County, g2.Name.Type }, g2.MyCount }

使用它:

new ProcessedType
{ 
    Name = new  MyType { g.Key.City, g.Key.County, g2.Name.Type }, 
    MyCount = g2.MyCount
}

为什么会出现这个错误?那么,编译器应该如何知道您实际引用ProcessedType而不是任何其他可能具有相同属性MyTypüeMyCount的类型?编译器无法猜测此处推断的类型,特别是没有从匿名类型到ProcessedType的隐式转换。

编辑:我脑海中引用我的第一部分的唯一假设是一个隐含类型的数组,你也可以写new[] { 1 },这将被隐含地声明为int[]

答案 2 :(得分:1)

试试这个

var type2 = type1.GroupBy(i => new { i.City, i.County, i.Type })
        .Select(group => new { Name = group.Key, MyCount = group.Count() })
        .OrderBy(x => x.Name).ThenByDescending(x => x.MyCount)
        .GroupBy(g => new { g.Name.City, g.Name.County })
        .Select(g => g.Select(g2 =>
        new ProcessedType{ Name = new MyType { City = g.Key.City, County = g.Key.County, Type = g2.Name.Type }, MyCount = g2.MyCount })).Take(1000).ToList();
相关问题