从列表中以年和月的方式对名称进行分组

时间:2012-03-25 10:43:50

标签: c# asp.net datetime collections

我创建了一个具有datetime数据类型和其他字符串属性的类的类。

public class name1
{
public DateTime dob { get; set; }
public string name { get; set; }
}

然后页面加载创建了一个列表

    DateTime d1 = new DateTime(1989, 5, 12);
    DateTime d2 = new DateTime(1989, 5, 26);
    DateTime d3 = new DateTime(1989, 3, 12);
    DateTime d4 = new DateTime(1986, 3, 21);
    DateTime d5 = new DateTime(1990, 8, 19);

    List<name1> randmoptn=new List<name1>();
    name1 n1=new name1();
    n1.name="rachit";
    n1.dob=d1;
    name1 n2=new name1();
    n2.name="abhinav";
    n2.dob=d2;
    name1 n3=new name1();
    n3.name="mandeep";
    n3.dob=d3;
    name1 n4=new name1();
    n4.name="jasmeet";
    n4.dob=d4;
    name1 n5=new name1();
    n5.name="rajat";
    n5.dob=d5;
    randmoptn.Add(n1);
    randmoptn.Add(n2);
    randmoptn.Add(n3);
    randmoptn.Add(n4);
    randmoptn.Add(n5);

现在我想要 所需的输出应为

year 1986

month 3

21/3/1986 jasmeet

year 1989

month 3

12/3/1989 mandeep

month 5 12/5/1989 rachit

26/5/1989 abhinav

year 1990

month 8

19/8/1990 rajat

2 个答案:

答案 0 :(得分:1)

如果您想要的输出如下

  • DoB with Name

然后做这样的事情

foreach item in YourList  
{  
   print item.dob.year; // this will return year in integer format
   print item.dob.month; // this will return month in integer format
   print item.dob; // this will return DoB as dateformat, do whatever formating you want 
   print item.name; // this will return Name as String  
}
如果需要,

在同一行打印DoB和名称

答案 1 :(得分:0)

    var q=from x in randmoptn
            group x by new { Year=x.dob.Year,Month=x.dob.Month} into month 
            group month by month.Key.Year into year
            select new { Year=year.Key,Months=year.OrderBy (y =>y.Key.Month )};

    foreach (var year in q) {
        Console.WriteLine("year {0}",year.Year);
        foreach (var month in year.Months) {
            Console.WriteLine("month {0}",month.Key.Month);
            foreach (var item in month) {
                Console.WriteLine("{0:dd/MM/yyyy},{1}",item.dob,item.name);
            }

        }
    }