C# 如何确定集合是否包含特定类型的项?
各位,我有个问题, 如何确定集合是否包含特定类型的项? 例如,我有一个ItemControl的ItemCollectionC# 如何确定集合是否包含特定类型的项?,c#,wpf,collections,C#,Wpf,Collections,各位,我有个问题, 如何确定集合是否包含特定类型的项? 例如,我有一个ItemControl的ItemCollection var items = comboBox.Items; 我需要知道我的问题是Items集合中的哪种类型的项目 例如,我需要确定 Items是字符串类型的项的集合 或DependencyObject或其他类型 请帮我解决这个问题。 提前感谢。列表类型=(从组合框中的项。项选择项。GetType()).Distinct(); foreach (object i
var items = comboBox.Items;
我需要知道我的问题是Items集合中的哪种类型的项目
例如,我需要确定
Items是字符串类型的项的集合
或DependencyObject或其他类型
请帮我解决这个问题。
提前感谢。列表类型=(从组合框中的项。项选择项。GetType()).Distinct();
foreach (object item in comboBox.Items)
{
if (item.GetType() == typeof(string))
{
//DoYourStuff
}
}
这将生成组合框项目中显示的所有类型的列表
如果只想测试列表中是否出现一种特定类型,可以执行以下操作:
bool containsStrings = comboBox.Items.OfType<string>.Any()
bool containsDependencyObjects = comboBox.Items.OfType<DependencyObject>.Any()
bool containsStrings=comboBox.Items.OfType.Any()
bool containsDependencyObjects=comboBox.Items.OfType.Any()
使用Linq轻松:
var itemsOfTypeString = comboBox.Items.OfType<string>();
var itemsOfTypeDependencyObject = comboBox.Items.OfType<DependencyObject>();
var itemsOfTypeString=comboBox.Items.OfType();
var itemsOfTypeDependencyObject=comboBox.Items.OfType();
那么,您的实现到底在哪里失败?对不起,我仍然不理解您的问题。您当前的方法有什么问题?请参阅问题和问题标题中的更新Lei join@Heinzi了解您的问题。Items[i].GetType()将返回位置[i]中的项的类型,您可以将其与typeof(string)或typeof(DependencyObject)进行比较。。。
var itemsOfTypeString = comboBox.Items.OfType<string>();
var itemsOfTypeDependencyObject = comboBox.Items.OfType<DependencyObject>();