linq查询创建新对象

时间:2016-05-04 07:44:34

标签: c# linq

假设我有一个类层次结构,其中基本上每个类都由一个属性项(如字符串)和一个嵌套类的属性列表项组成:

<击>

<击>
public class Master
{ 
    public String myName;
    public List<Detail> myDetails;
}
public class Detail
{ 
    public String myDetailDescription;
    public List<DetailParts> parts;
}
public class DetailParts
{
    public int PartNumber;
    public String PartDescription;
}

<击>

现在我想有一个linq查询给我 由这些元素组成的对象列表

public class Result
{
    public String myName; // from Master
    public String myDetailDescription; // from Detail
    public int PartNumber; // from DetailParts
}

这是一个愚蠢的问题,我知道,但我找不到有用的链接......

[编辑#1]:更好的代码示例:

public class Master
{ 
    public String myName;
    public List<Detail> myDetails = new List<Detail>();
}
public class Detail
{ 
    public String myDetailDescription;
    public List<DetailParts> parts = new List<DetailParts>();
}
public class DetailParts
{
    public int PartNumber;
    public String PartDescription;
}


// List of Masters
List<Master> master = new List<Master>();
// Two detail parts for the Details
DetailParts dp1 = new DetailParts { PartDescription = "dp1" };
DetailParts dp2 = new DetailParts { PartDescription = "dp2" };
// once again two details for the Master
Detail d1 = new Detail { myDetailDescription = "d1" };
Detail d2 = new Detail{ myDetailDescription = "d2"};
// Assign the Parts
d1.parts.Add(dp1);
d1.parts.Add(dp2);
d2.parts.Add(dp1);
d2.parts.Add(dp2);
Master m1 = new Master { myName = "m1" };
Master m2 = new Master { myName = "m2" };
m1.myDetails.Add(d1);
m1.myDetails.Add(d2);
m2.myDetails.Add(d1);
m2.myDetails.Add(d2);
master.Add(m1);
master.Add(m2);

// given a value for `myName` and `myDetailDescription` i  
// would be able to get a list with the `DetailParts` objects:

var t = master.Where(a => a.myName == "m2")
    .Select(a => a.myDetails).FirstOrDefault()
    .Where(b => b.myDetailDescription == "d1")
    .Select(c => c.parts).FirstOrDefault();

1 个答案:

答案 0 :(得分:4)

您正在寻找SelectMany

List<Result> results = masterList
    .SelectMany(m => m.myDetails
        .SelectMany(d => d.parts
            .Select(dp => new Result
            {
                PartNumber = dp.PartNumber,
                myDetailDescription = d.myDetailDescription,
                myName = m.myName
            })))
    .ToList();

使用LINQ查询语法的更易读的版本:

var resultQuery = from m in masterList
                  from d in m.myDetails
                  from dp in d.parts
                  select new Result
                  {
                    PartNumber = dp.PartNumber,
                    myDetailDescription = d.myDetailDescription,
                    myName = m.myName
                  };
List<Result> results = resultQuery.ToList();