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
?
Well it depends if you need to use the first
filterwhen youDoSomething(which it seems like you do). But yes, you could shorten this code using LINQ.If you need the
filter:If not, you could use the Any method.