Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Query WindowCollection [closed]

Tags:

c#

linq

I'm having elementary problem with trying to query System.Windows.WindowCollection at some point in my code i have

WindowCollection z =   Application.Current.Windows;

and would like to do z.Any();

like image 354
user5606505 Avatar asked Nov 25 '25 16:11

user5606505


2 Answers

The definition of WindowCollection Class is as follows

public sealed class WindowCollection : ICollection, IEnumerable

As you may see, it doesn't implement IEnumerable<Window>, so in order to have access to the most of the Enumerable extension methods, you need first to use Enumerable.Cast like this

z.Cast<Window>().Any();
like image 133
Ivan Stoev Avatar answered Nov 27 '25 06:11

Ivan Stoev


LINQ works only with IEnumerable<T> interface. WindowCollection impliments only IEnumerable. There two options:

  • Cast<T>() - this return IEnumerable but if collection has element which can't be casted to T exception will thrown.
  • OfType<T>() - this returns IEnumerable. It skips element which can't be casted to T, that is why I prefer OfType.

Application.Current.Windows.OfType<Window>().Any();

like image 45
EvilCore2Duo Avatar answered Nov 27 '25 05:11

EvilCore2Duo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!