简体   繁体   English

如何使用 LINQ 有条件地创建新的字符串数组?

[英]How to create new string array conditionally with LINQ?

I have a string array like the following:我有一个字符串数组,如下所示:

string[] myStrings = new string[] {"P1111111F","N1111110","Z2","P1111111F","Z1111110"};

How can I use LINQ to check each string is length = 8 and ends with "0" to get the following:如何使用 LINQ 检查每个字符串的长度 = 8 并以“0”结尾以获得以下信息:

result: {"N","Y","N","N","Y"};

myStrings could be much longer with repeating strings so I'd like to achieve a solution that doesn't reprocess strings its already considered once. myStrings 使用重复字符串可能会更长,所以我想实现一个不重新处理已经考虑过的字符串的解决方案。

The straightforward way:直截了当的方法:

string[] results = myStrings
    .Select(s => s?.Length == 8 && s.EndsWith("0") ? "Y" : "N")
    .ToArray();

The micro optimized way avoiding doubling algorithm of ToArray :避免ToArray算法加倍的微优化方式:

string[] results = new string[myStrings.Length];
for(int i = 0; i < myStrings.Length; i++)
{
    string s = myStrings[i];
    results[i] = s?.Length == 8 && s.EndsWith("0") ? "Y" : "N"; 
}

myStrings could be much longer with repeating strings so I'd like to achieve a solution that doesn't reprocess strings its already considered once. myStrings使用重复字符串可能会更长,所以我想实现一个不重新处理已经考虑过的字符串的解决方案。

I don't think that caching those results for example in a Dictionary<string, string> would help at all.我不认为将这些结果缓存在Dictionary<string, string>中会有所帮助。 The check if so easy and fast that any lookup would be less efficient.检查是否如此简单和快速,以至于任何查找都会降低效率。 You'd just waste memory.你只会浪费 memory。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM