简体   繁体   中英

Grouping the name in the manner of years and months from a list

i had created a class with two properties one of datetime datatype and other of string.

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

and then page load created a list

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

and now i wanted desired output should be

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

If your desired output is as below

  • Year
  • Month
  • DoB with Name

then do something like this

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  
}

print the DoB and Name in the same line if you want

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

        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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