如何在C#中找到元素长度最小的数组的索引值 [英] How to find the index value of array whose element length is minimum in C#

查看:98
本文介绍了如何在C#中找到元素长度最小的数组的索引值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 string [] test = {absc,abc,abcder,abcdg}; 





如何在c#中找到元素长度最小的数组的索引值





这里我应该得到1作为输出









先谢谢。



我尝试了什么:



< pre> string [] test = {absc,abc,abcder,abcdg}; 





如何在c#中找到元素长度最小的数组的索引值





这里我应该得到1作为输出









提前谢谢。

解决方案

这并不难,但是...它有作业的气味所以我不会给你任何代码!



所有你需要做的是:

1)创建两个变量:minLength(默认为int.MaxValue)和minIndex(默认为-1)

2)使用 for 循环来查看数组中的所有元素,其索引变量从0到长度减去1.

2.1)如果索引处的当前值小于minLength,则将其设置为新的minLength,并将minIndex设置为当前索引。

3)循环之后,minLength说明有多短最短的是,minIndex说它在哪里。



简单,没有?


如果你熟悉Linq ,您可以使用一行代码执行此操作。


  string  [ ] test = {  absc  abc  abcder  abcdg}; 
var smallest = Array.IndexOf(test,test.First(s = > s .Length == test.Min(st = > st.Length)));


string[] test = { "absc", "abc", "abcder", "abcdg" };



how to find the index value of array whose element length is minimum in c#



Here i should get 1 as a output





Thanks In advance.

What I have tried:

<pre>string[] test = { "absc", "abc", "abcder", "abcdg" };



how to find the index value of array whose element length is minimum in c#



Here i should get 1 as a output





Thanks In advance.

解决方案

This isn't difficult, but ... it smells of homework so I'll give you no code!

All you need to do is:
1) Create two variables: minLength (defaulted to int.MaxValue) and minIndex (defaulted to -1)
2) use a for loop to look at all elements in your array with a index variable that runs from 0 to the length minus 1.
2.1) If the current value at the index is shorter than minLength set that as the new minLength, and set minIndex to the current index.
3) After the loop, minLength says how short the shortest was, and minIndex says where it was.

Simple, no?


If you are familiar with Linq, you could do this with one line of code.

string[] test = { "absc", "abc", "abcder", "abcdg" };
var smallest = Array.IndexOf(test, test.First(s => s.Length == test.Min(st => st.Length)));


这篇关于如何在C#中找到元素长度最小的数组的索引值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆