简体   繁体   中英

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

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:

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:

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). But yes, you could shorten this code using LINQ.

If you need the filter :

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

If not, you could use the Any method.

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:

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;

Having shorter code doesn't mean more efficient, you should understand what these statements actually produce as IL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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