[英]How to get Value less than in a String of Arrays
string[] str = new string[] {"sun", "mon", "tue", "wed", "thu", "fri","sat"};
是否可以使用LINQ在输入字符串之前获取索引列表:即,如果输入字符串是thu
,我的结果应该是: sun,mon,tue,wed,thu
。
You can use the Take()
extension method: 您可以使用Take()
扩展方法:
str.Take(Array.IndexOf(str, "thu") + 1).ToArray();
// --> returns `["sun", "mon", "tue", "wed", "thu"]`
If you want the items before the input string you can write: 如果要在输入字符串之前输入项目,可以编写:
res = str.TakeWhile (s => s != "thu");
This will however not include thu
itself. 但是,这将不包括thu
本身。
But can by fixed by writing: 但是可以通过写来固定:
res = str.TakeWhile (s => s != "thu").Concat(new[]{"thu"});
But the fastest way of doing it would probably be: 但是最快的方法可能是:
var i = Array.IndexOf(str, "thu");
if(i != -1)
{
var target = new string[i + 1];
Array.Copy(str, target, i + 1);
}
You can try the IndexOf
with Where
method on a list instead of an array. 您可以在列表而不是数组上尝试IndexOf
with Where
方法。 Here is the code: 这是代码:
string[] str = new string[] { "sun", "mon", "tue", "wed", "thu", "fri", "sat" };
var strList = str.ToList();
var targetIndex = strList.IndexOf("thu");
var result = strList.Where((s, index) => index <= targetIndex).ToList();
//result = sun, mon, tue, wed, thu
var query = str.TakeWhile(s => s != "thu").Concat(new string[] { "thu" }).ToArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.