locked
How can i use linq to retrieve the index of a collection/array RRS feed

  • Question

  • User483055775 posted

    How can i use linq to retrieve the index of a collection/array when in the example below, I know the Age, Year, and CatDesc.  For example I want to do the Linq equivalent of

     

    var cIndex = Select ? from cBudget where Age = 50 and Year = 2003 and CatDesc = "Housing"

     

    Thanks

     

    DonnieS

    Thursday, August 1, 2013 6:43 PM

Answers

  • User-821857111 posted

    Why do you want the index of the item when you can get a reference to the item through a straightforward query?

    var item = cBudget.FirstOrDefault(i => i.Age == 50 && i.Year == 2003 && i.CatDesc == "Housing");

    But if you do want the index for some purpose, you have to write your own extension method to get that. See the accepted answer from Slaks here: http://stackoverflow.com/questions/2471588/how-to-get-index-using-linq
     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, August 2, 2013 12:26 AM

All replies

  • User483055775 posted

    Here is the collection in question.

     

     public class cBudget
     {
         public int    Age {get;set;}
         public int    Year {get;set;}
         public string CatDesc {get;set;}
         public string Desc {get;set;}
         public decimal Amount {get;set;}
         public string DesReq {get;set;}
         public double Inflation {get;set;}
     }
    
    Thursday, August 1, 2013 6:46 PM
  • User-821857111 posted

    Why do you want the index of the item when you can get a reference to the item through a straightforward query?

    var item = cBudget.FirstOrDefault(i => i.Age == 50 && i.Year == 2003 && i.CatDesc == "Housing");

    But if you do want the index for some purpose, you have to write your own extension method to get that. See the accepted answer from Slaks here: http://stackoverflow.com/questions/2471588/how-to-get-index-using-linq
     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, August 2, 2013 12:26 AM
  • User483055775 posted

    - I would use a crystal ball if it gives me the index - Thanks very much.

    Friday, August 2, 2013 12:31 AM
  • User483055775 posted

    Actually, I want the index to make changes to the row that fits that query  as in

     

    budget[index].Amount = NewlyUpdatedAmount

     

     

    Friday, August 2, 2013 12:43 AM
  • User-821857111 posted

    You would tyically do that like this:

    var item = cBudget.FirstOrDefault(i => i.Age == 50 && i.Year == 2003 && i.CatDesc == "Housing");
    if(item != null){
    item.Amount = NewlyUpdatedAmount;
    Friday, August 2, 2013 3:32 AM