简体   繁体   中英

Populate list of object using group by in LINQ

I've the following classes

public class R
{
    public Guid Id { get; set; }
    public string Title { get; set; }
    public int RNumber { get; set; }
    public int VNumber { get; set; }
}

public class RD
{
    public Guid RDId { get; set; }
}

public class RRDS
{
    public R R { get; set; }
    public string ProjectTitle { get; set; }
    public List<RD> RDs{ get; set; }
}

public class RRSDto
{
    public Guid Id { get; set; }
    public string Title { get; set; }
    public string ProjectTitle { get; set; }
    public int RNumber { get; set; }
    public int VNumber { get; set; }
    public Guid RDId { get; set; }
}

From the database i get the list of RRSDto. i need to convert the list of RRSDto to list of RRDS. The Id, Title, ProjectTile, RNumber, VNumber can be same but the RDId will be different.

This is what i've tried with LINQ:

var temp = (from r in rrs
            group r by new
            {
                r.Id,
                r.Title,
                r.ProjectTitle,
                r.RNumber,
                r.VNumber,
            } into gcs
            select new RRDS()
            {
                R = new R()
                {
                    Id = gcs.Key.Id,
                    Title = gcs.Key.Title,
                    RNumber = gcs.Key.RNumber,
                    VNumber = gcs.Key.VNumber
                },
                ProjectTitle = gcs.Key.ProjectTitle,
                RDs = new List<RD>()
                {
                    new RD()
                    {
                        RDId = gcs.ToList().Select(g =>  g.RDId).FirstOrDefault()
                    }
                }
            }).ToList();

Instead of FirstOrDefault i want the list of RDIds. How do i get it using LINQ?

Thanks in advance, Suyog

如果您想要所有RDId然后仅使用Select对其进行投影,由于您不在该组中寻找第一个RDId ,因此我看不到使用FirstOrDefault的任何理由。

 ,RDs = gcs.Select(g => new RD { RDId = g.RDId }).ToList()

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