开发者

How to select a subset from a DataTable through LINQ?

I am new to LINQ. I have the following DataTable

Name   Date       price1  price2
string DateTime   decimal decimal
Jan09  14.01.2009开发者_运维百科 10.0    12.0
Feb09  14.01.2009 11.0    13.0
Jan09  15.01.2009 10.0    12.5
Feb09  15.01.2009  9.0    10.0
Jan09  18.01.2009 10.0    12.5
Feb09  18.01.2009  9.0    10.0

Name and Date are the primary compound key.

I want to select all Names for each Date, then iterate through the new collection and select the next date.

var subCollection =  tab.Rows.Cast<DataRow>().Select(r1 => r1["Date"]).Select<string>(r2 => r2["Name"])
foreach (DataRow row in subCollection)
{
    // do something with row
}

My Linq expression is wrong


I think what you want is to group by your Date, then look at all the Names for a given date, then most onto the next.

If that is the case, you want to use the Linq group syntax...

var query = from row in table.AsEnumerable()
        group row by row["Date"] into g
        select g;

You can find a lot of examples online for doing various things with the Linq group syntax. The thing I find important is realizing that you can group by multiple columns and still apply aggregate functions like Sum, Max, or Count using the following syntax:

var query = from row in table.AsEnumerable()
    group row by new { Date = row["Date"], Price1 = row["Price1"] }  into g
    select new
    {
        Date = g.Key.Date,
        Price = g.Key.Price1,
        Count = g.Count()
    };
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜