如何比较两个无序序列(列表和数组)是否相等?

发布于 2024-11-06 11:00:34 字数 240 浏览 0 评论 0原文

我有字符串数组,例如 string str[] = {"a", "b"}

List; lst = 新列表<字符串>; {"a", "b"}

如何确保字符串数组和列表包含相同的值。 注意:这些值可以是任意顺序,但必须具有相同的频率。

谁能告诉我如何在 LINQ 中做到这一点?

谢谢。

I have string array say string str[] = {"a", "b"}

and List<string> lst = new List<string> {"a", "b"}

How can I make sure that both string array and list contains the same values. Note: The values can be in any order but must have the same frequency.

Can anyone tell me how to do it in LINQ?

Thanks.

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

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

发布评论

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

评论(4

活泼老夫 2024-11-13 11:00:34

也许我错过了一些东西,但为什么你不直接对

  • 两者进行排序(因为顺序与你无关)
  • 将结果与 SequenceEqual() 进行比较

保存 Jason 的字典方法(显然,应该也可以工作)并且对我来说似乎更自然/容易?

①:https://learn.microsoft.com/ en-us/dotnet/api/system.linq.enumerable.sequenceequal

Maybe I'm missing something, but why don't you just

  • Sort both (since order is irrelevant for you)
  • Compare the results with SequenceEqual()¹

Saves the dictionary approach of Jason (which, obviously, should work as well) and seems more natural/easy to me?

①: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.sequenceequal

染年凉城似染瑾 2024-11-13 11:00:34

接受的答案对我来说似乎有点尴尬。为什么你不能这样做:

bool equals = str.OrderBy(s => s).SequenceEquals(lst.OrderBy(t => t));

The accepted answer seems somewhat awkward to me. Why can't you just do:

bool equals = str.OrderBy(s => s).SequenceEquals(lst.OrderBy(t => t));
平生欢 2024-11-13 11:00:34

好的,由于顺序并不重要,但频率很重要,因此您需要对每个键进行计数,然后检查生成的键/计数对是否相等:

var first = str.GroupBy(s => s)
               .ToDictionary(g => g.Key, g => g.Count());

var second = lst.GroupBy(s => s)
                .ToDictionary(g => g.Key, g => g.Count());

bool equals = first.OrderBy(kvp => kvp.Key)
                   .SequenceEquals(second.OrderBy(kvp => kvp.Key));

Okay, since order does not matter but frequncies do, you need to count each key, and then check that the resulting pairs of keys/counts are equal:

var first = str.GroupBy(s => s)
               .ToDictionary(g => g.Key, g => g.Count());

var second = lst.GroupBy(s => s)
                .ToDictionary(g => g.Key, g => g.Count());

bool equals = first.OrderBy(kvp => kvp.Key)
                   .SequenceEquals(second.OrderBy(kvp => kvp.Key));
陌路终见情 2024-11-13 11:00:34

您可以使用 Enumerable.SequenceEqual

  string[] str =new [] {"a", "b"};
  List<string> lst = new List<string> {"a", "b"};
  bool result=str.SequenceEqual(lst);

You can use Enumerable.SequenceEqual

  string[] str =new [] {"a", "b"};
  List<string> lst = new List<string> {"a", "b"};
  bool result=str.SequenceEqual(lst);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文