Check Object type in List of Objects

后端 未结 4 1137
刺人心
刺人心 2021-01-28 13:03

Got a WPF Form with a StackPanel containing Expanders with StackPanels in it.


    

        
相关标签:
4条回答
  • 2021-01-28 13:12

    If I understand You correctly you can use this LINQ Expression

    var w = tmpList.Where(x=>x.IsTypeOf(StackPanel)).SingleOrDefault();
    
    0 讨论(0)
  • 2021-01-28 13:23

    You can use OfType<> to filter for just a specific type in a list. I understand that you want to loop through all the StackPanels (in the list), so you can do something like this:

    foreach(var panel in tmpList.OfType<StackPanel>()){
        //your work here ...
    }
    

    If you want to check if there is any StackPanel, then use this:

    if(tmpList.OfType<StackPanel>().Any()){
        //...
    }
    
    0 讨论(0)
  • 2021-01-28 13:27

    I would do something like this: use the Enumerable.OfType<>()

    More info: https://msdn.microsoft.com/en-us/library/vstudio/bb360913(v=vs.100).aspx

    foreach(var stackpanel in tmpList.OfType<StackPanel>())
    {
        // search for the label. (the same trick)
        var myLabel = stackpanel.Children.OfType<Label>().FirstOrDefault();
    
        // if the label can't be found, continue to the next one.
        if(myLabel == null)
            continue;
    
        myLabel.Content = "whatever";
    }
    
    0 讨论(0)
  • 2021-01-28 13:29

    Not many questions answer this part of the question. "Now i must know if the list contains an object of type stackpanel." Which can be achieved through the following:

    if (tmpList.Any(x=>x.IsTypeOf(StackPanel)))
    {
         //returns true if there are any stack panels in the list 
    }
    
    0 讨论(0)
提交回复
热议问题