使用 LINQ 过滤字符串
Filter a string using LINQ
我在编码面试中遇到了这个问题,我需要过滤字符串列表和 return 一个字符串以 "L" 开头的排序枚举,但据记载,如果字符串列表在调用 Filter 方法后修改,没有使用 toList(),我不明白最后一个条件。
目前我可以找到以 "L" 开头的排序字符串。
/**C# method**/
public static IEnumerable<string> Filter(List<string> strings)
{
return strings.Where(i => i.StartsWith("L") || i.StartsWith("l")).OrderBy(x => x);
}
我需要理解最后一句的意思:
如果在不使用 ToList() 的情况下调用 Filter 方法后修改了字符串列表,则您的解决方案应该有效。
如果您了解 Linq 在幕后的工作原理,很可能会看到他们在这里的目的。
IEnumerable 接口不仅允许循环某些内容,还可以用于延迟执行。这意味着实际代码不会在枚举它之前执行(例如循环或 .ToList()
调用)。
那么这和你的问题有什么关系呢?好吧,因为它在循环之前没有执行,我们实际上可以用列表调用 Filter()
方法并保留对可枚举的引用,然后在我们实际循环可枚举之前更改源列表。
using System;
using System.Collections.Generic;
using System.Linq;
class MainClass {
public static void Main (string[] args) {
var list = new List<string> { "Lambda", "Aardvark", "Lexicon" };
// This is now just an IEnumerable that will
// call Where() and OrderBy() when it is enumerated.
var filteredEnum = Filter(list);
list.RemoveAt(1);
list.Add("Leisure");
// This is where the actual enumeration happens
// which then executes the Linq methods.
foreach(var word in filteredEnum)
Console.WriteLine(word);
}
public static IEnumerable<string> Filter(List<string> strings)
{
return strings.Where(i => i.StartsWith("L") || i.StartsWith("l")).OrderBy(x => x);
}
}
在 https://repl.it/repls/CautiousFrankLaw 上试用。
因此,在下次面试之前,您可能希望多看一下 deferred execution and linq,这样下次您就可以取得好成绩。
我在编码面试中遇到了这个问题,我需要过滤字符串列表和 return 一个字符串以 "L" 开头的排序枚举,但据记载,如果字符串列表在调用 Filter 方法后修改,没有使用 toList(),我不明白最后一个条件。
目前我可以找到以 "L" 开头的排序字符串。
/**C# method**/
public static IEnumerable<string> Filter(List<string> strings)
{
return strings.Where(i => i.StartsWith("L") || i.StartsWith("l")).OrderBy(x => x);
}
我需要理解最后一句的意思: 如果在不使用 ToList() 的情况下调用 Filter 方法后修改了字符串列表,则您的解决方案应该有效。
如果您了解 Linq 在幕后的工作原理,很可能会看到他们在这里的目的。
IEnumerable 接口不仅允许循环某些内容,还可以用于延迟执行。这意味着实际代码不会在枚举它之前执行(例如循环或 .ToList()
调用)。
那么这和你的问题有什么关系呢?好吧,因为它在循环之前没有执行,我们实际上可以用列表调用 Filter()
方法并保留对可枚举的引用,然后在我们实际循环可枚举之前更改源列表。
using System;
using System.Collections.Generic;
using System.Linq;
class MainClass {
public static void Main (string[] args) {
var list = new List<string> { "Lambda", "Aardvark", "Lexicon" };
// This is now just an IEnumerable that will
// call Where() and OrderBy() when it is enumerated.
var filteredEnum = Filter(list);
list.RemoveAt(1);
list.Add("Leisure");
// This is where the actual enumeration happens
// which then executes the Linq methods.
foreach(var word in filteredEnum)
Console.WriteLine(word);
}
public static IEnumerable<string> Filter(List<string> strings)
{
return strings.Where(i => i.StartsWith("L") || i.StartsWith("l")).OrderBy(x => x);
}
}
在 https://repl.it/repls/CautiousFrankLaw 上试用。
因此,在下次面试之前,您可能希望多看一下 deferred execution and linq,这样下次您就可以取得好成绩。