A.Oreo
A.Oreo

Reputation: 321

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.

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. But the result B is always empty.

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 B I 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?

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

Upvotes: 0

Views: 76

Answers (2)

Mahesh Malpani
Mahesh Malpani

Reputation: 2019

    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

Upvotes: 0

Sylence
Sylence

Reputation: 3083

You are not enumerating the Select.

These methods do not iterate the list unless they are specifcly asked to, for example by calling ToList()

However of course you can use foreach:

foreach( var item in A.OrderByDescending(o=>o.Date).GroupBy(o=>o.Symbol) )
{
   B.Add( item.Key, item.ToList() );
}

Upvotes: 2

Related Questions