简体   繁体   English

重写为SortedList

[英]Rewrite into a SortedList

public class MyClass
{
    public DateTime Date;
    public string Symbol { get; set; }
    public decimal Close { get; set; }
}

I want to collect by Symbol (one symbol corresponds a list of dates) and rewrite List<MyClass> A as SortedList<string, List<MyClass>> B. 我想按Symbol收集(一个符号对应一个日期列表),然后将List<MyClass> A重写为SortedList<string, List<MyClass>> B.

SortedList<string, List<MyClass>> B = new SortedList<string, List<MyClass>>();
           A.OrderByDescending(o => o.Date).GroupBy(o => o.Symbol)
            .Select(o => {
                B.Add(o.Key, o.ToList());
                return 1;
            });

Here I can not use Foreach, so I use Select instead. 在这里我不能使用Foreach,所以我使用Select代替。 But the result B is always empty. 但是结果B始终为空。

I am not sure whether I should open a new question, I never expect your answer is so fast......but they are almost similar, after obtain the SortedList BI need take some filtration as follow, but if I add the ToList)() I can no longer call for the o.Key or how to keep the SortedList structure after the linq ? 我不确定我是否应该打开一个新问题,我从没想到你的答案会这么快……但是它们几乎是相似的,在获得SortedList BI之后,需要进行如下过滤,但是如果我添加ToList)()我不能再要求o.Key或在linq之后如何保留SortedList结构?

B.Select(o => o.Value.Where(p => p.Date <= today).Take(volDay))
                .Where(o => o.Count() == volDay).ToList()
                ForEach(o => C.Add(o.Key, o.ToList()); 

You are not enumerating the Select. 您不是在枚举选择。

These methods do not iterate the list unless they are specifcly asked to, for example by calling ToList() 除非特别要求这些方法(例如,通过调用ToList()),否则它们不会迭代列表。

However of course you can use foreach: 当然,您可以使用foreach:

foreach( var item in A.OrderByDescending(o=>o.Date).GroupBy(o=>o.Symbol) )
{
   B.Add( item.Key, item.ToList() );
}
    List<MyClass> A = new List<MyClass>();
        A.Add(new MyClass() { Close = 0.2m, Symbol = "Test1", Date = DateTime.Now });
        A.Add(new MyClass() { Close = 0.3m, Symbol = "Test1", Date = DateTime.Now });
        A.Add(new MyClass() { Close = 0.1m, Symbol = "Test2", Date = DateTime.Now });
        A.Add(new MyClass() { Close = 0.2m, Symbol = "Test2", Date = DateTime.Now });
        SortedList<string, List<MyClass>> B = new SortedList<string, List<MyClass>>();
        A.OrderByDescending(o => o.Date).GroupBy(o => o.Symbol).ToList()
            .ForEach(o => B.Add(o.Key, o.ToList()));
        Console.WriteLine(B.Count);
        Console.ReadKey();

Tested the code. 测试了代码。 You should be using foreach loop instead if you want to perform some operation on all records 如果要对所有记录执行某些操作,则应改用foreach循环

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM