0

I'm facing a weird problem, I haven't programmed much with c# and only started recently, so I apologise in advance if the question is in fact just a beginner mistake.

int i = 0;
var index = from x in (
                from v in Category.Items 
                select new { Key = i++, Value = v }) 
            where ((MenuCategory) x.Value).id == menuItems[items.SelectedIndex].category 
            select x.Key;

I'm trying to get the index of a specific object in Category.Items[] (where the field id is a specific value, menuItems[items.SelectedIndex].category)

juharr
  • 31,741
  • 4
  • 58
  • 93
user1494162
  • 316
  • 1
  • 3
  • 10

1 Answers1

5

LINQ queries should not cause side effects like this. You can get what you want with method syntax and the overload of Select:

var selectedCatId = menuItems[items.SelectedIndex].category;
var indexes = Category.Items
    .Select((c, index) => new { Key = index, Value = c })
    .Where(x => ((MenuCategory)x.Value).id == selectedCatId)
    .Select(x => x.Key);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • this worked, thank you. can you please elaborate on why it's not a good idea to have LINQ queries with side effects? – user1494162 Feb 07 '17 at 14:01
  • 1
    @user1494162: well, you have provided a good example. Queries are supposed to collect informations provided in one or multiple sources. If this query also modifies something it often depends on how the query is executed(f.e. if you have an `OrderBy` or `Where` and in which order they appear). If someone changes this logic ´he might also change the effect but unknowingly. – Tim Schmelter Feb 07 '17 at 14:04