使用LINQ获取符合日期的所有记录

时间:2017-05-17 13:02:54

标签: c# linq

我有一张这样的桌子。

Date         |Name  |Id|Item   |
23-March-2017|Vinod |1|USB     |
02-May-2017  |Sureka|2|Cable   |
23-March-2017|Mahesh|6|Mouse   |
24-May-2017  |Raju  |7|Keyboard|
09-May-2017  |Raju  |2|Cable   |
23-March-2017|Mahesh|6|Mouse   |
02-May-2017  |Ganga |7|Keyboard|

我希望根据表Uisng LINQ Like

中的日期获取数据
24-May-2017
    Raju-Keyboard
09-May-2017
    Raju-Cable
02-May-2017
    Sureka-Cable
    Ganga-Keyboard
23-March-2017
     Vinod-USB
     Mahesh-Cable
     Mahesh-Mouse

2 个答案:

答案 0 :(得分:0)

context.Table.Select(o => new { Date = o.Date, Text = o.Name + "-" + o.Item }).GroupBy(o => o.Date);

如果没有我知道变量名等等,应该可以做到这一点。

答案 1 :(得分:0)

我建议使用字典

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace ConsoleApplication55
{
    class Program
    {

        static void Main(string[] args)
        {

            DataTable dt = new DataTable();
            dt.Columns.Add("Date", typeof (DateTime));
            dt.Columns.Add("Name", typeof (string));
            dt.Columns.Add("Id", typeof (int));
            dt.Columns.Add("Item", typeof (string));

            dt.Rows.Add(new object[] { DateTime.Parse("23-March-2017"), "Vinod", 1, "USB"});
            dt.Rows.Add(new object[] { DateTime.Parse("02-May-2017"), "Sureka", 2, "Cable"});
            dt.Rows.Add(new object[] { DateTime.Parse("23-March-2017"), "Mahesh",6, "Mouse"});
            dt.Rows.Add(new object[] { DateTime.Parse("24-May-2017"), "Raju",7, "Keyboard"});
            dt.Rows.Add(new object[] { DateTime.Parse("09-May-2017"), "Raju", 2, "Cable"});
            dt.Rows.Add(new object[] { DateTime.Parse("23-March-2017"), "Mahesh", 6, "Mouse"});
            dt.Rows.Add(new object[] { DateTime.Parse("02-May-2017"), "Ganga", 7, "Keyboard"});

            Dictionary<DateTime, List<string>> dict = dt.AsEnumerable().GroupBy(x => x.Field<DateTime>("Date")).ToDictionary(x => x.Key, y => y.Select(z => z.Field<string>("Name") + "-" + z.Field<string>("Item")).ToList());
        }


    }

}