如何确定集合是否包含特定类型的项目?

时间:2021-05-29 04:15:58

everyone, I have a question, How to determine if a collection contains items of specific type? For example I have ItemCollection of an ItemControl

大家好,我有一个问题,如何确定一个集合是否包含特定类型的项目?例如,我有ItemControl的ItemCollection

var items = comboBox.Items;

I need to know what type of item in the Items collection that is my question

我需要知道Items集合中哪个类型的项目是我的问题

for example I need to determine if Items is collection of items type of string or DependencyObject or other type.

例如,我需要确定Items是否是字符串或DependencyObject或其他类型的项类型的集合。

Help me please resolve this issue. Thanks in advance.

帮帮我解决这个问题。提前致谢。

3 个解决方案

#1


3  

List<Type> types = (from item in comboBox.Items select item.GetType()).Distinct();

This yields a list of all the types that appear in your combo box items.

这将生成组合框项目中显示的所有类型的列表。

If you just want to test whether one specific type appears in your list, you can do the following:

如果您只想测试列表中是否显示某个特定类型,则可以执行以下操作:

bool containsStrings = comboBox.Items.OfType<string>.Any()
bool containsDependencyObjects = comboBox.Items.OfType<DependencyObject>.Any()

#2


4  

easy with Linq:

Linq很容易:

var itemsOfTypeString = comboBox.Items.OfType<string>();
var itemsOfTypeDependencyObject = comboBox.Items.OfType<DependencyObject>();

#3


2  

        foreach (object item in comboBox.Items)
        {
            if (item.GetType() == typeof(string))
            {
                //DoYourStuff
            }
        }

#1


3  

List<Type> types = (from item in comboBox.Items select item.GetType()).Distinct();

This yields a list of all the types that appear in your combo box items.

这将生成组合框项目中显示的所有类型的列表。

If you just want to test whether one specific type appears in your list, you can do the following:

如果您只想测试列表中是否显示某个特定类型,则可以执行以下操作:

bool containsStrings = comboBox.Items.OfType<string>.Any()
bool containsDependencyObjects = comboBox.Items.OfType<DependencyObject>.Any()

#2


4  

easy with Linq:

Linq很容易:

var itemsOfTypeString = comboBox.Items.OfType<string>();
var itemsOfTypeDependencyObject = comboBox.Items.OfType<DependencyObject>();

#3


2  

        foreach (object item in comboBox.Items)
        {
            if (item.GetType() == typeof(string))
            {
                //DoYourStuff
            }
        }