c# - C# 中的父子流畅 Linq 查询?

标签 c# .net linq

我在流畅的 LINQ 中遇到了一个问题,用于将父项和子项选择为一个 Ienumerable < anonymous type> .

为了简单起见:

  • 有一个列表 commanders (各地区指挥官)。

  • 每个指挥官都有自己的List of Soldiers 。 (每个Soldier都有一个bool属性IsCanWinWar和一个他用来战斗的Tool)

我想列出每位指挥官(谁有一个或多个士兵可以获胜 war )一个 tool该士兵使用的名字。

我不在乎指挥官是否拥有超过一名能够赢得 war 的士兵。

指挥官所需要的只是 tool (不管使用哪种工具)来自它的一名士兵(他可以赢得 war )。

输出是Ienumerable < anonymous type>其中匿名类型如下:

{ 
  theCommander = [commanderObject] , 
  theToolName = [the tool name ]
} 

我用 selectMany 做了一些事情但它又长又丑。

是否有任何简短的查询(流畅查询)可以以更短的方式产生相同的结果?

public class Commander
    {
    public List<Soldier> lstSoldiers =new List<Soldier>(); //from db actually.
    }


    public class Soldier
    {
      public bool IsCanWinWar { get; set; }
      public string Tool { get; set; }
    }



void Main()
{
  List<Commander> lstCommanders = new List<Commander>(); //data source is actually from db.
  var MyIernumerableOfAnonymouseTypes= ?
}

最佳答案

var MyIernumerableOfAnonymouseTypes = 
   lstCommanders.Select(c => new { 
                    theCommander = c, 
                    theToolName = c.lstSoldiers.Where(s => s.IsCanWinWar)
                                               .Select(s => s.Tool)
                                               .FirstOrDefault() })
                .Where(x => x.theToolName != null);

如果没有能够赢得 war 的士兵,那么工具就无效。选择后过滤掉那些指挥官即可。

顺便说一句,我认为 Soldiers 是一个更好的属性名称,然后 lstSoldiers (它没有前缀,并且是 PascalCase)。

关于c# - C# 中的父子流畅 Linq 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15245569/

相关文章:

c# - 接口(interface)作为一个用于继承的原因,而不是实现者

c# - 将wav文件转换为单声道

c# - Linq:返回具有给定类型的第一个实例的方法

c# - 您如何知道何时通过 XML 序列化加载?

c# - 为什么 Asp.net MVC 不能区分具有不同参数的两个 Action ?

c# - 在 linq to entities 中将 int 转换为字符串

.net - 如何转换为 m4v

javascript - 为 javascript 转义 .NET 正则表达式模式

c# - 使用 LINQ 构建链表

c# - 解析 json 并获取 null 异常,无论我做了多少次 null 检查