List Index Search

前端 未结 2 518
忘掉有多难
忘掉有多难 2020-12-21 23:28

I have a List item

List xmlValue = new List();

In this I have Item {\"English\",\"Spanish\",\"French\",\

相关标签:
2条回答
  • 2020-12-22 00:12
    List<string> xmlValue = new List<string>() 
                     {"English", "Spanish", "French", "Hindi", "English", "English"};
    
    string search = "English";
    
    int[] result = xmlValue.Select((b, i) => b.Equals(search) ? i : -1)
                           .Where(i => i != -1).ToArray();
    
    0 讨论(0)
  • 2020-12-22 00:27

    I'd opt against using the LINQ extension methods in this case and use an "old-fashioned" loop:

    string search = "English";
    
    var foundIndices = new List<int>(xmlValue.Count);
    for (int i = 0; i < xmlValue.Count; i++) {
        if (xmlValue[i] == search) {
            foundIndices.Add(i);
        }
    }
    

    It's simply more readable like this in my opinion; also, the foundIndices list never holds any unwanted values.

    0 讨论(0)
提交回复
热议问题