使用LINQ重构WPF,grid.Children迭代方法

时间:2017-01-21 12:31:00

标签: linq

我的目标是将此foreach逻辑转换为单个LINQ查询。

foreach (var anyItem in gridReference.Children)
{
    var enumerableCheck = anyItem as ListBox; 

    if (enumerableCheck != null)
    {
        foreach (var collectionItem in enumerableCheck.Items)
        {
            //check collectionItem is of type T
        }
    } 

    else
    {                    
        //check anyItem is of type T
    }
}

我尝试用这种重构来学习linq,但语法错误是真实的,因为我已经习惯了C#。另外我不知道如何在linq中分配一个工作变量,这导致了不断的转换。

尝试:

IEnumerable <T> genericQuery = from UIElement element1 in gridReference.Children
                               where (element1 as ListBox) != null
                               from item in (element1 as ListBox).Items
                               where (item as T) != null
                               select (item as T)

                               from UIElement element2 in gridReference.Children
                               where element2 as T != null
                               select element2;  

2 个答案:

答案 0 :(得分:2)

我认为在linq中使用let子句来检查该转换是一个很好的例子。 https://msdn.microsoft.com/en-us/library/bb383976.aspx

为了确保您只返回适合T的项目,您可以使用OfType<T>

List<T> result = (from element1 in gridReference.Children
                        let el1ListBox = element1 as ListBox
                        where el1ListBox != null 
                        select el1ListBox.Items.OfType<T>()).ToList();

编辑:

根据评论:

List<T> result = (from element1 in gridReference.Children.OfType<ListBox>().ToList()
                        select element1.Items.OfType<T>()).ToList();

答案 1 :(得分:0)

由于madOX的鼓励回复,我测试了一个有效的查询。

IEnumerable <T> genericQuery = (from element1 in gridReference.Children.OfType <ListBox>()
                                from boxItem in element1.Items.OfType <T>()
                                select boxItem)

                                .Concat (from element2 in gridReference.Children.OfType <T>()
                                select element2);