简体   繁体   English

在C#中有条件的foreach循环

[英]foreach loop with condition in c#

I have this foreach loop in c#, since i am new to c#, i was wondering if this can be written shorter (have the condition part of the loop 我在c#中有这个foreach循环,因为我是c#的新手,所以我想知道是否可以将其写得更短(具有循环的条件部分)

foreach (PagerPageFilterInformation filter in PageFilterInformation)
{
    if (filter.Ancestor == myParent)
    {
        DoSomething()...//Using filter
        break;
    }
}

I tried doing : 我试着做:

PagerPageFilterInformation filter = PageFilterInformation.FirstOrDefault(filter => filter.Ancestor == myParent);
if(filter != null)
{
DoSomething()...}

But it didnt work. 但是它没有用。 could it be because the class: 可能是因为该类:

PagerPageFilterInformation

Inherits from the class : 从类继承:

PageFilterInformation

?

If DoSomething() method does not use found filter: 如果DoSomething()方法不使用找到的过滤器:

if (PageFilterInformation.Any(filter => filter.Ancestor == myParent))
{
   DoSomethng();
}

EDIT: Update since new requirements was provided in comments 编辑:由于评论中提供了新的要求,因此进行了更新

If you need pass found filter into the DoSomething() method: 如果需要将找到的过滤器传递到DoSomething()方法中:

var filter = PageFilterInformation.FirstOrDefault(f => f.Ancestor == myParent);
if (filter != null)
{
   DoSomething(filter);
}

Well it depends if you need to use the first filter when you DoSomething (which it seems like you do). 好吧,这取决于您在执行DoSomething时是否需要使用第一个filter (看起来确实如此)。 But yes, you could shorten this code using LINQ. 但是可以,您可以使用LINQ缩短此代码。

If you need the filter : 如果您需要filter

var filter = PageFilterInformation.FirstOrDefault(filter => filter.Ancestor == myParent);
if(filter != null)
{
    DoSomething()...
}

If not, you could use the Any method. 如果不是,则可以使用Any方法。

if (PageFilterInformation.Any(filter => filter.Ancestor == myParent)
{
    DoSomething()...
}
foreach (PagerPageFilterInformation filter in PageFilterInformation.Where(f => f.Acestor==myParent))
        {
                DoSomething()...
        }

Since you're using the filter variable, I would use this construct: 由于您使用的是filter变量,因此我将使用以下构造:

var filter = PageFilterInformation.FirstOrDefault(f => f.Ancestor == myParent);
if (filter != null)
{
    DoSomething(filter);
}

Code becomes easier to read since I don't have to read through the loop and figure out that it stops at the first found element. 代码变得更容易阅读,因为我不必遍历循环并弄清楚它停在第一个找到的元素上。

If PageFilterInformation is an IEnumerable you can use the System.Linq's extension Where method; 如果PageFilterInformation是IEnumerable,则可以使用System.Linq的扩展Where方法。

Having shorter code doesn't mean more efficient, you should understand what these statements actually produce as IL. 拥有较短的代码并不意味着效率更高,您应该了解这些语句实际上作为IL产生的结果。

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

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