Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将这个双foreach循环转换为lambdas?_C#_Linq_Lambda_Foreach - Fatal编程技术网

C# 如何将这个双foreach循环转换为lambdas?

C# 如何将这个双foreach循环转换为lambdas?,c#,linq,lambda,foreach,C#,Linq,Lambda,Foreach,这是否有一种方法可以使这些foreach循环只一个lambda表达式 private int getNextEventId() { int numOfEvents = 0; foreach (MonthModel eventMonth in eventsForAllMonths) { foreach (DayModel eventDay in eventMonth.AllDays)

这是否有一种方法可以使这些foreach循环只一个lambda表达式

    private int getNextEventId()
    {
        int numOfEvents = 0;

        foreach (MonthModel eventMonth in eventsForAllMonths)
        {
            foreach (DayModel eventDay in eventMonth.AllDays)
            {
                numOfEvents += eventDay.CalEvents.Count;
            }
        }

        return numOfEvents + 1;
    }
我以
ForEach()
为生,所以:

eventsForallMonths.ForEach(em=>em.ForEach(ed=>numOfEvents+=ed.CalEvents.Count));
试试这个:

    private int getNextEventId()
    {
        int numOfEvents = eventsForAllMonths.SelectMany(eventMonth => eventMonth.AllDays).Aggregate(0, (current, eventDay) => current + eventDay.CalEvents.Count);

        return numOfEvents + 1;
    }
这个怎么样

return
    (from m in eventsForAllMonths
    from d in m.AllDays
    select d.CalEvents.Count).Sum() + 1;

在lambda中改造一下怎么样

List<Item> listItem = new List<Item>();
foreach (StackPanel sp in spPhotos.Children)
{
    foreach(Item item in sp.Children)
    {
        listItem.Add(item);
    }
    sp.Children.Clear();
}
spPhotos.Children.Clear();
List listItem=new List();
foreach(照片子对象中的StackPanel sp)
{
foreach(sp.Children中的项目)
{
列表项。添加(项);
}
sp.Children.Clear();
}
spPhotos.Children.Clear();

eventsForAllMonths
可能不在
列表中
这可能有效,也可能无效,具体取决于eventsForAllMonths的类型。ForEach仅可用于列表。如果eventsForAllMonths是其他的东西,那么它就失败了。对我来说,像在lambda中那样修改状态似乎很讨厌。我不敢相信有人-1 me:)OP想要lambda,而你把他推到扩展方法中。tsk tskeventsForAllMonths是一个静态列表。这只是为了测试。你有没有故意说“只有一个λ”?没有人给出“只有一个”答案……我不太明白你的问题。但似乎很多人都明白我的意思:)你说的是一个lambda,意思是一个=>
return
    (from m in eventsForAllMonths
    from d in m.AllDays
    select d.CalEvents.Count).Sum() + 1;
List<Item> listItem = new List<Item>();
foreach (StackPanel sp in spPhotos.Children)
{
    foreach(Item item in sp.Children)
    {
        listItem.Add(item);
    }
    sp.Children.Clear();
}
spPhotos.Children.Clear();