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

本文关键字:类型 包含特 何确定 集合 是否 | 更新日期: 2023-09-27 18:13:45

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

的ItemCollection
var items = comboBox.Items;

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

例如

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

请帮我解决这个问题。

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

easy with Linq:

var itemsOfTypeString = comboBox.Items.OfType<string>();
var itemsOfTypeDependencyObject = comboBox.Items.OfType<DependencyObject>();
List<Type> types = (from item in comboBox.Items select item.GetType()).Distinct();

这将生成组合框项中出现的所有类型的列表。

如果你只想测试一个特定的类型是否出现在你的列表中,你可以这样做:

bool containsStrings = comboBox.Items.OfType<string>.Any()
bool containsDependencyObjects = comboBox.Items.OfType<DependencyObject>.Any()
        foreach (object item in comboBox.Items)
        {
            if (item.GetType() == typeof(string))
            {
                //DoYourStuff
            }
        }