user1494162 user1494162 - 1 year ago 56
C# Question

Why does my LINQ query always return 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
(where the field id is a specific value,

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download