Find index of a value in an array

前端 未结 8 1522
傲寒
傲寒 2020-11-29 22:41

Can linq somehow be used to find the index of a value in an array?

For instance, this loop locates the key index within an array.

for (int i = 0; i &         


        
相关标签:
8条回答
  • 2020-11-29 23:09

    Just posted my implementation of IndexWhere() extension method (with unit tests):

    http://snipplr.com/view/53625/linq-index-of-item--indexwhere/

    Example usage:

    int index = myList.IndexWhere(item => item.Something == someOtherThing);
    
    0 讨论(0)
  • 2020-11-29 23:10
    int keyIndex = words.TakeWhile(w => !w.IsKey).Count();
    
    0 讨论(0)
  • 2020-11-29 23:14
    int index = -1;
    index = words.Any (word => { index++; return word.IsKey; }) ? index : -1;
    
    0 讨论(0)
  • 2020-11-29 23:17

    This solution helped me more, from msdn microsoft:

    var result =  query.AsEnumerable().Select((x, index) =>
                  new { index,x.Id,x.FirstName});
    

    query is your toList() query.

    0 讨论(0)
  • 2020-11-29 23:19

    Try this...

    var key = words.Where(x => x.IsKey == true);
    
    0 讨论(0)
  • 2020-11-29 23:24

    If you want to find the word you can use

    var word = words.Where(item => item.IsKey).First();
    

    This gives you the first item for which IsKey is true (if there might be non you might want to use .FirstOrDefault()

    To get both the item and the index you can use

    KeyValuePair<WordType, int> word = words.Select((item, index) => new KeyValuePair<WordType, int>(item, index)).Where(item => item.Key.IsKey).First();
    
    0 讨论(0)
提交回复
热议问题