加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 将匿名类型的列表转换为字典>

发布时间:2020-12-16 00:16:08 所属栏目:百科 来源:网络整理
导读:我有一个创建本地List object的函数.对象是匿名类型.我需要在Dictionary string,SortedList DateTime,double中返回这些结果. 数据列表如下所示. { Security = "6752 JT",Date = {1/17/2011 12:00:00 AM},zScore = 1 }{ Security = "6753 JT",zScore = 2 }{ S
我有一个创建本地List< object>的函数.对象是匿名类型.我需要在Dictionary< string,SortedList< DateTime,double>>中返回这些结果.

数据列表如下所示.

{ Security = "6752 JT",Date = {1/17/2011 12:00:00 AM},zScore = 1 }
{ Security = "6753 JT",zScore = 2 }
{ Security = "6754 JT",zScore = 3 }
{ Security = "6752 JT",Date = {1/18/2011 12:00:00 AM},Date = {1/19/2011 12:00:00 AM},zScore = 3 }

我想使用LINQ将这些结果放入Dictionary< string,double>>字典的键是安全性,值是包含安全性的所有日期/ z分数值的SortedList.

当LINQ是自定义对象时,我可以在LINQ中执行此操作,但是如何使用匿名类型对象执行此操作?

注意:此查询最初是以不必要的复杂且措辞不当的方式发布的.这可能是没有人回答的原因!我要包含链接,以防你想知道为什么输出是这种形式.
C# LINQ Z-Score query output to a Dictionary<string,SortedList<DateTime,double>>

解决方法

所以基本上你问的是如何从对象中取消匿名类型?

首先,我建议不要使用List< object>只是…创建一个自定义类.

public class SecurityScore {
    public string Security { get; set; }
    public DateTime Date { get; set; }
    public int ZScore { get; set; }
}

但是,如果出于任何原因需要这样做,请尝试Jon Skeet的这种方法:

I’ve always known that it’s perfectly easy to return an instance of an anonymous type by declaring that the method will return object. However,it hadn’t occurred to me before today that you can actually cast back to that type afterwards. Of course,you can’t just use a normal cast expression – that requires the name of the type to be known at compile-time. But you can do a cast in a generic method… and you can use type inference to supply a type argument… and two anonymous type instance creation expressions will use the same type within the same assembly if the order,names and types of the properties are the same.

如果你想探索他的解决方案,请查看他关于这个主题的blog post.

为了完整起见,我将在此处发布他的代码:

static class GrottyHacks
{
    internal static T Cast<T>(object target,T example)
    {
        return (T) target;
    }
}

class CheesecakeFactory
{
    static object CreateCheesecake()
    {
        return new { Fruit="Strawberry",Topping="Chocolate" };
    }

    static void Main()
    {
        object weaklyTyped = CreateCheesecake();
        var stronglyTyped = GrottyHacks.Cast(weaklyTyped,new { Fruit="",Topping="" });

        Console.WriteLine("Cheesecake: {0} ({1})",stronglyTyped.Fruit,stronglyTyped.Topping);            
    }
}

我必须承认,虽然我不喜欢装箱/取消装箱匿名类型的想法,但他的方法非常棒,占用了相对较少的代码.

所以,既然我已经给你一个可能的解决方案,我必须问 – 为什么你这样做,而不是创建一个简单的类?

编辑:同样为了完整性,我将使用Jon Skeet的解决方案实现您的特定问题:

void Main()
{
    // Create a list of (boxed) anonymous objects
    var securitiesBoxed = new List<object>() {
        new { Security = "6752 JT",Date = DateTime.Parse("1/17/2011 12:00:00 AM"),zScore = 1 },new { Security = "6753 JT",zScore = 2 },new { Security = "6754 JT",zScore = 3 },new { Security = "6752 JT",Date = DateTime.Parse("1/18/2011 12:00:00 AM"),Date = DateTime.Parse("1/19/2011 12:00:00 AM"),zScore = 3 }
    };

    // Now,to convert to a Dictionary<string,double>>...
    var securitiesUnboxed = securitiesBoxed.Select(x => Cast(x,new { Security = "",Date = new DateTime(),zScore = 0 }))
        .GroupBy(x => x.Security)
        .ToDictionary(x => x.Key,x => x.OrderBy(y => y.Date));
}

// This is the static method that will cast our anonymous type
internal static T Cast<T>(object target,T example)
{
    return (T) target;
}

在LINQPad,上面的代码产生以下数据:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读