我有一组字符串:"Apple", "Mange", "Pineapple"
我想得到长度最长的单词的索引。例如,2
对应于最长的单词"Pineapple"
。
答案 0 :(得分:3)
要获得名称最长的水果,请执行以下操作:
var fruits = new List<String> { "Apple", "Mange", "Pineapple" };
var longestName = (from fruit in fruits
orderby fruit.Length descending
select fruit).First();
var index = fruits.IndexOf(longestName);
作为一个lambda,没有特别的原因:
var fruits = new List<String> { "Apple", "Mange", "Pineapple" };
var longestName = fruits.OrderByDescending(e => e.Length).First();
var index = fruits.IndexOf(longestName);
答案 1 :(得分:1)
以下内容也可以起作用:
var maxItem = fruits
.Select((fruit, index) => new { Length = fruit.Length, Index = index })
.Aggregate((max, next) => (next.Length > max.Length) ? next : max);
var maxIndex = maxItem.Index;