转换列表< object>的匿名类型到字典< string,SortedList< DateTime,double>> [英] Transform a List<object> of anonymous type to a Dictionary<string, SortedList<DateTime, double>>

查看:102
本文介绍了转换列表< object>的匿名类型到字典< string,SortedList< DateTime,double>>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数创建一个本地的 List< object> ,其中对象是一个匿名类型。我需要在 Dictionary< string,SortedList< DateTime,double>> 中返回这些结果。



数据是这样的列表。

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

我想使用LINQ将这些结果放在一个字典< string,SortedList< DateTime,double>> 中字典的关键是安全性,值是一个包含a的SortedList这个安全性的日期/ z分数值。



我可以在LINQ中做一个自定义对象,但是如何使用匿名类型对象?



注意:此查询最初发布在一个不必要的复杂和不太方便的方式。这可能是为什么没有人回答!我正在包括链接,以防您想了解为什么输出为这种形式。

C#LINQ Z-score查询输出到字典< string,SortedList< DateTime,double>>

解决方案

所以基本上你在问如何从对象 / p>

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

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

但是,如果由于任何原因您需要这样做,请尝试此方法从Jon Skeet:


我一直都知道,返回一个匿名类型的实例是很容易的,声明方法将返回目的。但是,今天以前我并没有想到,你实际上可以再次回到那种类型。当然,你不能只使用一个普通的转换表达式 - 这就需要在编译时知道类型的名称。但是,您可以使用通用方法进行转换,并且可以使用类型参数来提供类型参数,如果命令,名称和类型,两个匿名类型的实例创建表达式将在同一个程序集中使用相同的类型的属性是一样的。


如果你想探索他的解决方案,请查看他的博客文章



为了完整,我将在这里发布他的代码:

  static class GrottyHacks 
{
内部静态T Cast< T>(对象目标,T示例)
{
return(T)target;
}
}

class CheesecakeFactory
{
静态对象CreateCheesecake()
{
return new {Fruit =Strawberry ,Topping =Chocolate};
}

static void Main()
{
对象weaklyTyped = CreateCheesecake();
var strongTyped = GrottyHacks.Cast(weaklyTyped,
new {Fruit =,Topping =});

Console.WriteLine(芝士蛋糕:{0}({1}),
strongTyped.Fruit,strongTyped.Topping);
}
}

我必须承认,虽然我不是就像拳击/拆箱一个匿名类型的想法一样,他的方法是非常棒的,并且占用了相对较少的代码行。



所以,现在我给了你一个可能的解决方案,我必须问 - 你为什么这样做,而不是创建一个简单的课程?



编辑:为了完整起见,以下是使用Jon Skeet解决方案实现您的特定问题的方法:

  void Main()
{
//创建(boxed)匿名对象的列表
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,Date = DateTime.Parse (1/17/2011 12:00:00 AM),zScore = 2},
new {Security =6754 JT,Date = DateTime.Parse(1/17/2011 12:00: 00 AM),zScor e = 3},
new {Security =6752 JT,Date = DateTime.Parse(1/18/2011 12:00:00 AM),zScore = 1},
new { Security =6753 JT,Date = DateTime.Parse(1/18/2011 12:00:00 AM),zScore = 2},
new {Security =6754 JT,Date = DateTime。解析(1/18/2011 12:00:00 AM),zScore = 3},
new {Security =6752 JT,Date = DateTime.Parse(1/19/2011 12:00 :00 AM),zScore = 1},
new {Security =6753 JT,Date = DateTime.Parse(1/19/2011 12:00:00 AM),zScore = 2}
new {Security =6754 JT,Date = DateTime.Parse(1/19/2011 12:00:00 AM),zScore = 3}
};

//现在,要转换为字典< string,SortedList< DateTime,double>> ...
var securitiesUnboxed = securitiesBoxed.Select(x => Cast(x,新的{Security =,Date = new DateTime(),zScore = 0}))
.GroupBy(x => x.Security)
.ToDictionary(x => x.Key, x => x.OrderBy(y = y.Date));
}

//这是静态方法,将抛出我们的匿名类型
内部静态T Cast< T>(对象目标,T示例)
{
return(T)target;
}

LINQPad ,上述代码产生以下数据:




I have a function that creates a local List<object> where the object is an anonymous type. I need to return these results in Dictionary<string, SortedList<DateTime, double>>.

The data is the the list looks like this.

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

I would like to use LINQ to place these results into a Dictionary<string, SortedList<DateTime, double>> where the dictionary's key is the Security, and the value is a SortedList containing all the date/z-score values for the security.

I can do this in LINQ when it is a custom object, but how do you do it with an anonymous type object?

Note: This query was originally posted in an unnecessarily complicated, and poorly phrased way. Which is probably why no one answered it! I'm including the link in case you wanted to see why the output is in this form.
C# LINQ Z-Score query output to a Dictionary<string, SortedList<DateTime, double>>

解决方案

So basically you're asking how to unbox an anonymous type from object?

First of all, I recommend not using a List<object> and just ... creating a custom class.

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

However, if for whatever reason you need to do this, try this approach from 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.

If you want to explore his solution, check out his blog post on the subject.

For completeness, I will post his code here:

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

I must admit that, while I don't really like the idea of boxing/unboxing an anonymous type, his approach is pretty awesome, and takes up relatively few lines of code.

So, now that I've given you a possible solution, I must ask -- why are you doing it this way, as opposed to creating a simple class?

Edit: Also for completeness, here's how I would implement your particular problem using Jon Skeet's solution:

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", Date = DateTime.Parse("1/17/2011 12:00:00 AM"), zScore = 2 },
        new { Security = "6754 JT", Date = DateTime.Parse("1/17/2011 12:00:00 AM"), zScore = 3 },
        new { Security = "6752 JT", Date = DateTime.Parse("1/18/2011 12:00:00 AM"), zScore = 1 },
        new { Security = "6753 JT", Date = DateTime.Parse("1/18/2011 12:00:00 AM"), zScore = 2 },
        new { Security = "6754 JT", Date = DateTime.Parse("1/18/2011 12:00:00 AM"), zScore = 3 },
        new { Security = "6752 JT", Date = DateTime.Parse("1/19/2011 12:00:00 AM"), zScore = 1 },
        new { Security = "6753 JT", Date = DateTime.Parse("1/19/2011 12:00:00 AM"), zScore = 2 },
        new { Security = "6754 JT", Date = DateTime.Parse("1/19/2011 12:00:00 AM"), zScore = 3 }
    };

    // Now, to convert to a Dictionary<string, SortedList<DateTime, 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;
}

In LINQPad, the above code results in the following data:

这篇关于转换列表&lt; object&gt;的匿名类型到字典&lt; string,SortedList&lt; DateTime,double&gt;&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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