score:7

Accepted answer

In Silverlight, the UIElementCollection implements IEnumerable<T>, but the UIElementCollection in WPF implements IEnumerable, not IEnumerable<T>. If you want to use LINQ here, you can use OfType<UIElement>() as an option:

foreach (var uiElement in Table.Children.OfType<UIElement>()
           .Where(x => Grid.GetColumn((Border)x) == Table.ColumnDefinitions.Count() - 1))
{
    //do something
}

score:3

Your code doesn't compile because UIElementCollection implements the non-generic collection interfaces, and Linq requires the generic collection interfaces.

You can use the Cast<T>() method to get an instance of IEnumerable<T> and then use Linq:

var children = Table.Children.Cast<UIElement>();
foreach (var uiElement in children .Where(x => Grid.GetColumn((Border)x) == Table.ColumnDefinitions.Count() - 1))
{
   //do something
}

score:5

The problem is that UIElementCollection does not implement the generic IEnumerable<T> :

public class UIElementCollection : IList, ICollection, IEnumerable

While the Enumerable.Where extension method requires the generic version:

public static IEnumerable<TSource> Where<TSource>(
    this IEnumerable<TSource> source,
    Func<TSource, int, bool> predicate
)

So, the solution is to cast the elements first:

foreach (var uiElement in Table.Children.OfType<UIElement>().Where(x => Grid.GetColumn((Border)x) == Table.ColumnDefinitions.Count() - 1))
{
}

Related Articles