如何在 C# 中使用 lambda 表达式在嵌套的 foreach 语句中表示条件语句



我正在使用嵌套的foreach语句在嵌入式列表上执行一些功能...即类属性,它们本身是包含列表的类。我想使用 ling 和 lambda 表达式来做到这一点

采取以下方法

public int GetCount1()
{
    int count1 = 0;
    int count2 = o;
    //This is the Setup code
    FirstClass fc = new FirstClass
    {
        FirstList = new List<SecondClass>
        {
            new SecondClass
            {
                SecondList = new List<ThirdClass>
                {
                    new ThirdClass
                    {
                        ThirdList = new List<FisrtStruct>
                        {
                            new FisrtStruct { int1=1, string1="one" },
                            new FisrtStruct{int1=2, string1="two" },
                            new FisrtStruct{ int1=3, string1="three" }
                        }
                    }
                }
            }
        }
    };
    foreach (var item in fc.FirstList)
    {
        foreach (var item2 in item.SecondList)
        {
            foreach (var item3 in item2.ThirdList)
            {
                if (item3.int1 > 1)
                {
                    count1++;
                }
            }
        }
    }
    // I want something along the lines of
    fc.FirstList
        .ForEach(f => 
            fc.FirstList.ForEach(fl => 
                fl.SecondList.ForEach(sl => 
                    sl.ThirdList.ForEach(tl => t1.int1 > 1 { count2++}  ))));
    return "count1@ " + count1 + " and count2: " + count2;
}

我本质上想复制在 count2 上增加 count1 的功能,但使用更流畅的 lambda 表达式。

下面是组件类

class FirstClass
{
    internal List<SecondClass> FirstList { get; set; }
}
class SecondClass
{
    public List<ThirdClass> SecondList { get; set; }
}
class ThirdClass
{
    internal List<FisrtStruct> ThirdList { get; set; }
}
struct FisrtStruct
{
    internal int int1 { get; set; }
    internal string string1 { get; set; }
}

也许你想要的是这样的:

int count = fc.FirstList.SelectMany(f => f.SecondList).SelectMany(s => s.ThirdList).Count(t => t.Int1 > 1);

也许兰德·兰登更快。

每个foreachList.ForEach都可以转换为 LINQ 调用,可以是查询形式的.Select()调用,也可以转换为from。 无论如何,List.ForEach仅适用于列表,并且除了foreach之外不会执行任何操作

嵌套的foreach呼叫可以变成:

var count= ( from item in fc.FirstList
             from item2 in item.SecondList
             from item3 in item2.ThirdList
             where (item3.int1 > 1)
             select item3
           ).Count();

相当于嵌套from s 是SelectMany()

var count = fc.FirstList
              .SelectMany(item=>item.SecondList)
              .SelectMany(item=>item.ThirdList)
              .Where(item=>item.int1>1)
              .Count();

计数本身可以有一个谓词,它节省了一行代码:

var count = fc.FirstList
              .SelectMany(item=>item.SecondList)
              .SelectMany(item=>item.ThirdList)
              .Count(item=>item.int1>1);

var count= ( from item in fc.FirstList
             from item2 in item.SecondList
             from item3 in item2.ThirdList
             select item3
           ).Count(item3.int1 > 1);

我认为这可以做到:

return fc.FirstList  
      .Select(i1 => i1.SecondList      //within each FirstList, look at the SecondList property
          .Select(i2 => i2.ThirdList   //within each SecondList, look at the ThirdList property
              .Count(i3 => i3.int1 > 1) //get the count for one/each ThirdList
          ).Sum()                       //sum all the ThirdList counts 
       ).Sum();                         //sum all the SecondList counts

真的,你想要SelectMany()而不是Select().Sum().这段代码只是为了建立理解SelectMany()将做什么的桥梁,接下来会做什么......但是在我走那么远之前,其他人发布了解决方案的SelectMany()部分,我认为在我自己的答案中发布基本相同的代码是不对的。

我完成了这篇文章的大部分内容,因为我仍然认为将此代码展示为教学机会很有用。它更好地匹配循环所执行的操作,因此可以帮助了解 Linq 运算符和 lambda 的工作方式。

在安装了锐化器以获得一些指导后,我能够完成我的 虽然过程.下面是一个完整的工作控制台程序文件

using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication2
{
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(GetCount1());
        Console.ReadLine();
    }
static string GetCount1()
{
    int count1 = 0;
    int count2 = 0;
    int count3 = 0;
    FirstClass fc = new FirstClass
        {
            FirstList = new List<SecondClass>
            {
                new SecondClass
                {
                    SecondList = new List<ThirdClass>
                    {
                        new ThirdClass
                        {
                            ThirdList = new List<FisrtStruct>
                            {
                                new FisrtStruct { Int1= 1, String1= "one" },
                                new FisrtStruct{ Int1 = 2, String1= "two" },
                                new FisrtStruct{ Int1= 3, String1 = "three" }
                            }
                        }
                    }
                }
            }
        };
        foreach (var item in fc.FirstList)
        {
            foreach (var item2 in item.SecondList)
            {
                foreach (var item3 in item2.ThirdList)
                {
                    if (item3.Int1 > 1)
                    {
                        count1++;
                    }
                }
            }
        }

    count2 = (from item in fc.FirstList from item2 in item.SecondList from item3 in item2.ThirdList select item3).Count(item3 => item3.Int1 > 1);
    // Solution:
    fc.FirstList
        .ForEach(f => fc.FirstList
            .ForEach(fl => fl.SecondList
                .ForEach(sl => sl.ThirdList
                    .ForEach(tl =>
                    {
                        if (tl.Int1 > 1)
                        {
                            count3++;
                        }
                    }
                    ))));

    return "count1: " + count1 + " and count2: " + count2 + " and count3: " + count3;
    }

}
class FirstClass
{
    internal List<SecondClass> FirstList { get; set; }
}
class SecondClass
{
    public List<ThirdClass> SecondList { get; set; }
}
class ThirdClass
{
    internal List<FisrtStruct> ThirdList { get; set; }
}
struct FisrtStruct
{
    internal int Int1 { get; set; }
    internal string String1 { get; set; }
}
}

希望它对某人有所帮助

最新更新