简体   繁体   English

如何在LINQ中编写此代码块?

[英]How do I write this block of code in LINQ?

I need to use linq as many times as possible and I have no idea how to use linq in this type of method. 我需要尽可能多地使用linq,而且我不知道如何在这种类型的方法中使用linq。

I've tried some code from certain webs however none of them worked 我已经尝试了某些网站上的一些代码,但是它们都不起作用

List<MemorableD> memorables = new List<MemorableD>();
    List<StateMD> states = new List<StateMD>();
    void Find(List<MemorableD> selected)
    {
        for (int i = 0; i < states.Count; i++)
        {
            for (int j = 0; j < memorables.Count; j++)
            {
                if (states[i].Month == memorables[j].Month && states[i].Day == memorables[j].Day)
                {
                    MemorableD select = new MemorableD(memorables[j].Year, memorables[j].Month, memorables[j].Day, memorables[j].Event, states[i].Event);
                    selected.Add(select);
                }
            }
        }
    }

I need to write this add method with LINQ 我需要用LINQ编写此添加方法

Try to break down your problem. 尝试解决您的问题。 If you were to analyse your loops, you are iterating over the States and Memorables, and creating instances of MemorableD where State and Memorable have the same Month and Day and latter adding them to the List. 如果要分析循环,则要遍历State和Memorables,并创建MemorableD实例,其中State和Memorable具有相同的Month和Day,然后将它们添加到列表中。

Translating it to Linq, 将其翻译为Linq,

from StateMD state in states
from MemorableD memorable in memorables
    where state.Month == memorable.Month && state.Day == memorable.Day
let selectValue = new MemorableD(memorable.Year, memorable.Month, memorable.Day, memorable.Event, state.Event)
select selectValue

The second part of the problem is to add it to the List called selected. 问题的第二部分是将其添加到名为selected的列表中。 You can add an IEnumerable to selected using the AddRange method. 您可以使用AddRange方法将IEnumerable添加到所选对象。

So, combining the Linq statement with AddRange method, 因此,结合使用Linq语句和AddRange方法,

selected.AddRange(from StateMD state in states
                              from MemorableD memorable in memorables
                              where state.Month == memorable.Month && state.Day == memorable.Day
                              let selectValue = new MemorableD(memorable.Year, memorable.Month, memorable.Day, memorable.Event, state.Event)
                              select selectValue);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM