DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Trending

  • Blue Skies Ahead: An AI Case Study on LLM Use for a Graph Theory Related Application
  • A Deep Dive Into Firmware Over the Air for IoT Devices
  • The Full-Stack Developer's Blind Spot: Why Data Cleansing Shouldn't Be an Afterthought
  • Performing and Managing Incremental Backups Using pg_basebackup in PostgreSQL 17

LINQ and WMI results - why not?

By 
Denzel D. user avatar
Denzel D.
·
Jul. 13, 10 · Interview
Likes (0)
Comment
Save
Tweet
Share
11.9K Views

Join the DZone community and get the full member experience.

Join For Free

WMI (Windows Management Instrumentation) can be queried by using standard ManagementObjectSearcher and then going through the items in the collection via a foreach loop.

Seems simple enough. However, WMI results can also be queried via LINQ. For example, I instantiate a ManagementObjectSearcher that will get the data that is specific to Win32_Processor:

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Processor");

How would you generally go when you need to find an item in the collection above? Probably use a foreach loop, right?

In this case, you will probably use something very similar to this:

foreach (ManagementObject obj in searcher.Get())
{
// Action here
}

It works fine as long as you want to go through each item in the collection. However, what would you do if you needed to select only the items that fit a specific criteria that are already placed in the collection (this does not involve initial WMI query modification)?

Using an if statement is fine as long as you are querying against a single criteria pointer. But what if there are multiple parameters by which you want to select the needed instance of ManagementObject?

In case you want to make the object search more specific, you can change the asterisk to a specific property in the initial query. For the existing collection, you can use LINQ to simplify the process. The first possible LINQ query that comes to mind is probably this.

var unit = from x in searcher.Get()
select x;

In fact, this is valid LINQ syntax and it looks like it should work just fine. However, it does not apply to ManagementObjectSearcher. ManagementObjectCollection (that is returned by the Get method) does not implement a query pattern, therefore you cannot directly invoke it via a simple LINQ query.

The solution to this problem is quite simple – you need to explicitly declare the type of x that will be selected from the collection – it is a ManagementObject. To do this, modify the query to look like this:

var unit = from ManagementObject x in searcher.Get()
select x;

This will automatically generate an IEnumerable<ManagementObject> compatible collection that fits the criteria set in the searcher. Compared to a foreach loop, this method is more efficient because you can directly specify multiple criteria pointers. For example:

var unit = from ManagementObject c in searcher.Get()
where c.Properties["CpuStatus"].Value.ToString() == "1" && c.Path.ToString() == @"\\DENNIS-PC\root\cimv2:Win32_Processor.DeviceID=""CPU0"""
select c;

A similar query (although with a single criteria pointer) can be simplified this way:

var unit = searcher.Get().Cast<ManagementObject>().ToList().Where((c) => c.Properties["CpuStatus"].Value.ToString() == "1");

So instead of directly using where and select, I am building a lambda expression that pretty much does the same thing, only in a shorter manner. Also, I am directly casting the ManagementObjectCollection to a list, so it can be queried without explicit object declaration for x.

I generally prefer using LINQ instead of looping through the results for one reason – LINQ statements are very flexible and I can easily modify them to conform to new requirements or needs. WMI is just one of the areas where LINQ can make life a bit easier.

Windows Management Instrumentation

Opinions expressed by DZone contributors are their own.

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!