如何使用对象而不是匿名类型 [英] How to use objects instead of anonymous Types

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

问题描述

我有这些LINQ查询:

I have these LINQ queries :

        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设为非匿名类型?

As you see the 2nd query returns an anonymous type. But I want to use these queries in a method. So I can't return anonymous type. How can I make type2 as a non-anonymous type?

我为此准备了两个对象:

I have prepared two objects for that :

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;}
}

但是我不能正确使用它们,因为我可能在查询中放错了位置.您可以帮助我,以便我使第二个查询返回定义的对象吗?谢谢.

But I couldn't use them properly because I probably misplaced them in the query. Can you help me so that I can make the second query return a defined object? Thanks.

推荐答案

您的代码中已包含以下内容:

You have this in your code:

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

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

Which are still anonymous types. You have to put the actual type names in there to be able to return them:

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

看看您的代码,您还应该能够分配现有的Name:

Looking at your code, you should also be able to assign the existing Name too:

new ProcessedType { Name = g2.Name, g2.MyCount }

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

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