我决定第一次尝试使用LINQ来解决这个问题。
我第一次涉足LINQ的奇妙世界,结果看起来像这样:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
List<string> list = new List<string>()
{
"fred-064528-NEEDED1",
"xxxx",
"frederic-84728957-NEEDED2",
"sam-028-NEEDED3",
"-----",
"another-test"
};
var result =
from s in list
where (from c in s where c == '-' select c).Count() == 2
select s.Substring(s.LastIndexOf("-") + 1);
foreach (string s in result)
Console.WriteLine(s);
Console.WriteLine("Press Enter");
Console.ReadLine();
}
}
}
我希望知道如何改进上面的解决方案以满足这个虚构小例子。我对是否使用了最佳验证方法或如何本地化“Press Enter”等内容不太感兴趣;我只想利用此示例学习更多关于LINQ的知识。