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

时间:2011-11-07 08:59:20

标签: c# wpf collections

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

var items = comboBox.Items;

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

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

请帮我解决此问题。 提前谢谢。

3 个答案:

答案 0 :(得分:4)

Linq很容易:

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

答案 1 :(得分:3)

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()

答案 2 :(得分:2)

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