count objects of a certain type in a collection and use this as a string in a textbox

后端 未结 1 672
时光取名叫无心
时光取名叫无心 2021-01-28 09:10

I want to fill a textbox with the count+1 of a kind of figure in a collection. The collection is a Generic List of Figure, figure is an instance of a certain type of Figure.

1条回答
  •  说谎
    说谎 (楼主)
    2021-01-28 09:42

    Generic type parameters need to be specified at compile-time, but GetType() is a function called at run time, so this simply won't work. The error message indicates that the compiler is trying to interpret your code as figures.OfType < figure.GetType() ... which doesn't make much sense.

    You can do this:

    // Count figures whose type is exactly equal to the type of figure
    txtName.Text = figures.Count(x => figure.GetType() == x.GetType()).ToString();
    
    // Count figures whose type is equal to or a subtype of the type of figure
    txtName.Text = figures.Count(x => figure.GetType().IsAssignableFrom(x.GetType())).ToString();
    

    0 讨论(0)
提交回复
热议问题