简体   繁体   English

如何获得比数组字符串少的值

[英]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.

相关问题 如何在C#或Linq中比较大于或小于运算符值的两个字节数组? - How to compare two byte arrays with greater than or less than operator value in C# or Linq? 如果字符串的长度小于15,如何获取字符串的前15个字符或更少的字符? - How can I get the first 15 characters of a string or less if the string is less than 15 in length? 如何将小于1的字符串(“ 0.25500000”)转换为十进制? - How to Convert string (“0.25500000”) less than 1 to Decimal? 如何使用IEnumerable.Max扩展从小于输入值的双打列表中获取最大值 - How to get max value from list of doubles that are less than an input value using IEnumerable.Max extensions 如何检查字符串的整数值是否小于LINQ中的值? - How can I check if the integer value of a string is less than something in LINQ? 当字符串的字符索引小于起始索引时,如何获取它的索引? - How do you get the index of a character in a string when it's less than your starting index? 如何允许大于和小于sqldatasource中的字符串参数 - How to allow greater than and less than in sqldatasource string parameter 如何获得等于或小于突出显示那些数据的图表数据点值 - How to get chart data points value with equal or less than to highlight those data 如何生成小于/大于长度的字符串 - How to generate a string with less than / more than length 如何在 Azure 移动服务中获取值小于特定限制的元素数量 - How to get the number of elements with value less than a particular limit in Azure Mobile Services
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM