LINQ 不以 on List开头

发布于 2024-11-05 11:59:09 字数 163 浏览 1 评论 0原文

我有一个列表其中有五个字符串:

abc
def
ghi
jkl
mno

我有另一个字符串“pq”,我需要知道列表中的每个字符串是否不以“pq”开头 - 我将如何使用 LINQ (.NET 4.0) 做到这一点?

I have a List<string> with five strings in it:

abc
def
ghi
jkl
mno

I have another string, "pq", and I need to know if each string in the list does not start with "pq" - how would I do that with LINQ (.NET 4.0)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

白鸥掠海 2024-11-12 11:59:09

两个选项:任何全部。您应该使用哪一个取决于您认为更具可读性:

var allNonPq = myList.All(x => !x.StartsWith("pq"));
var notAnyPq = !myList.Any(x => x.StartsWith("pq"));

它们在效率上实际上是等效的 - 两者都会在到达以“pq”开头的元素(如果有)时立即停止。

如果您发现自己经常这样做,您甚至可以编写自己的扩展方法:

public static bool None<T>(this IEnumerable<T> source, Func<T, bool> predicate)
{
    return !source.Any(predicate);
}

此时您将拥有:

var nonePq = myList.None(x => x.StartsWith("pq"));

当然,您是否发现比前两个更具可读性是个人喜好:)

Two options: Any and All. Which one you should use depends on what you find more readable:

var allNonPq = myList.All(x => !x.StartsWith("pq"));
var notAnyPq = !myList.Any(x => x.StartsWith("pq"));

These are effectively equivalent in efficiency - both will stop as soon as they reach an element starting with "pq" if there is one.

If you find yourself doing this a lot, you could even write your own extension method:

public static bool None<T>(this IEnumerable<T> source, Func<T, bool> predicate)
{
    return !source.Any(predicate);
}

at which point you'd have:

var nonePq = myList.None(x => x.StartsWith("pq"));

Whether you find that more readable than the first two is a personal preference, of course :)

浪菊怪哟 2024-11-12 11:59:09
bool noPQStart = !myList.Any( x=> x.StartsWith("pq"));
bool noPQStart = !myList.Any( x=> x.StartsWith("pq"));
装纯掩盖桑 2024-11-12 11:59:09

这将产生 IEnumerable类型的结果。

var strings = new string[] { ... };
var results = strings.Select(s => s.StartsWith("pq"));

This will produce results which is an IEnumerable<bool>

var strings = new string[] { ... };
var results = strings.Select(s => s.StartsWith("pq"));
尐籹人 2024-11-12 11:59:09
var notPq = from s in myList where  !s.StartsWith("pq") select s;

if (notPq.Any()) {
  // At least one item in list doesn't start with pq, possibly do something with each element that doesn't
}
var notPq = from s in myList where  !s.StartsWith("pq") select s;

if (notPq.Any()) {
  // At least one item in list doesn't start with pq, possibly do something with each element that doesn't
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文