Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将managementobjectcollection强制转换为IEnumerable<;IEnumerable<;IPropertyData>>;?_C# - Fatal编程技术网

C# 如何将managementobjectcollection强制转换为IEnumerable<;IEnumerable<;IPropertyData>>;?

C# 如何将managementobjectcollection强制转换为IEnumerable<;IEnumerable<;IPropertyData>>;?,c#,C#,如何将managementobjectcollection强制转换为IEnumerable,其中propertydata仅为名称和值 interface IPropertyData { string Name { get; } object Value { get; } } class ManagementObjectInfo : IManagementInfo { public IEnumerable<IEnumerable<IPropertyD

如何将managementobjectcollection强制转换为
IEnumerable
,其中propertydata仅为名称和值

interface IPropertyData
{

     string Name { get; }
     object Value { get; }
}

class ManagementObjectInfo : IManagementInfo
{


    public IEnumerable<IEnumerable<IPropertyData>> Get(string query)
    {
        ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);

        return  searcher.Get()  ;
    }


}
接口IPropertyData
{
字符串名称{get;}
对象值{get;}
}
类ManagementObjectInfo:IManagementInfo
{
公共IEnumerable Get(字符串查询)
{
ManagementObjectSearcher search=新的ManagementObjectSearcher(查询);
返回searcher.Get();
}
}

您不能直接强制转换引用,但可以相当轻松地使用LINQ:

public IEnumerable<IEnumerable<IPropertyData>> Get(string query)
{
    var searcher = new ManagementObjectSearcher(query);
    var results = searcher.Get();
    return results.Cast<ManagementBaseObject>()
        .Select(item => item.Cast<PropertyData>()
                            .Select(x => (IPropertyData)
                                         new PropertyDataImpl(x.Name, x.Value));
}
public IEnumerable Get(字符串查询)
{
var searcher=新的ManagementObjectSearcher(查询);
var results=searcher.Get();
返回结果。Cast()
.Select(item=>item.Cast()
.选择(x=>(IPropertyData)
新的PropertyDataImpl(x.Name,x.Value));
}
(其中,
PropertyDataImpl
IPropertyData
接口的简单实现。)

这样做的一个缺点是:它不执行任何处理。您可能希望将结果具体化为列表或其他内容,这样您就可以在处理过程中处理所有内容