簡體   English   中英

使用linq填充類列表

[英]Using linq to populate list of classes

我有一個類似於以下的表格:

Data {
    id varchar(50),
    pId uniqueidentifier ,
    fId uniqueidentifier ,
    xid uniqueidentifier,
    flag smallint 
}

該表包含許多重復的行,因為pId和fId是1:n關系,而fId與xId也是1:n關系。

我想查詢該表並填充一個obj,如下所示:

class P
{
    Guid id;
    List<F> fList; 
}

class F
{
    Guid id;
    List<X> xList; 
}


class X
{
    Guid id;
    byte flag; 
}

我正在學習Linq。 使用Linq從表中填充類P的任何解決方案都將有所幫助。

謝謝!

該查詢將返回IEnumerable<P> (不確定將smallint轉換為boolean但其他方法也可以使用)

var query = from p in context.Data
            group p by p.pId into gp
            select new P()
            {
                id = gp.Key,
                fList = (from f in gp
                         group f by f.fId into gf
                         select new F()
                         {
                             id = gf.Key,
                             xList = gf.Select(x => new X() { id = x.xid, 
                                                              flag = x.flag })
                                       .ToList()
                         }).ToList()
            };

評論:

gp將包含與某個pId對應的所有行,換句話說,它將返回與pId相關的所有fId。

gf將包含先前結果中與某個fId相關的所有行(即與fId相關的所有xid)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM