Get the index of a given item using LINQ [quick-tip]

UPDATE: Please see first comment to do this the "safe" way...

It took a bit for me to get comfortable enough with LINQ-to-objects to write ‘queries’ off the top of my head…but once you’re used to it you realize it’s much more concise, easier to interpret/read, and well..it’s less code.  Here are some real quick examples…

This first example selects the string array value as well as its position from the someItems array.  Note, the user of new{} creates a new generic type that has the properties ItemName and Position.  I could have called these two properties whatever I pleased, because I’m creating them at query-time.

string[] someItems = { "cat", "dog", "purple elephant", "unicorn" };

var selectedItems = someItems.Select((item, index) => new

{

ItemName = item,

Position = index

});

After you run this, selectedItems will look like this….

selItems 

And if you needed to just get the position as an int to use that for some other logic, your code may look like this..

int firstItem = someItems.Select((item, index) => new

{

ItemName = item,

Position = index

}).Where(i => i.ItemName == "purple elephant")

.First

.Position;

In which case, firstItem would equal 2.  Naturally, this is only the beginning of what LINQ to objects can do for you – but it definitely illustrates how LINQ can ease your daily coding.

Technorati Tags:,,,

This article is part of the GWB Archives. Original Author: Sanjay Uttam

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.