简体   繁体   中英

Retrieving Generic List Item index

I have a list as below. I would like to retrieve the indexes of all the items which have the value 1.

        List<int> listFilter = new List<int>();

        listFilter.Add(1);
        listFilter.Add(0);
        listFilter.Add(0);
        listFilter.Add(1);

I should be getting 0 and 3 for the sample data above.

The code below gives me an object of [value, index] pair. How do I modify this to just output a list which has only the indexes.

        var val = listFilter.Select((value, index) => new { Value = value, Index = index }).Where(item => item.Value == 1).ToList();

Thanks

Regards, Balan Sinniah

The problem is that in the initial Select clause you returned an anonymous type. To get back out the value you need an additional Select later on to filter back to that value.

var val = listFilter
  .Select((value, index) => new { Value = value, Index = index })
  .Where(item => item.Value == 1)
  .Select(item => item.Index)
  .ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM