最简单的合取(交集)代码
我有两个数组,我想要知道它们是否有共同元素的最简单方法。所以其实这个问题还得问。
string[] countries1 = new string[] { "USA", "Uruguay", "India", "UK"};
string[] countries2 = new string[] { "Urguay", "Argentina", "Brasil", "Chile" };
foreach (string country in countries1)
if (countries2.Contains(country))
return true;
return false;
- 让我知道
country1
国家/地区是否也在country2
数组中的最简单的 linq 查询是什么? - 将返回每个重复国家/地区的数组的最简单的 linq 查询是什么?
I have two arrays and I wnat the simplest way of knowing if they have elements in common. So actually this question have to questions.
string[] countries1 = new string[] { "USA", "Uruguay", "India", "UK"};
string[] countries2 = new string[] { "Urguay", "Argentina", "Brasil", "Chile" };
foreach (string country in countries1)
if (countries2.Contains(country))
return true;
return false;
- What's the simplest linq query that will let me know if any of the
country1
countries is also in thecountry2
array? - What's the simplest linq query that will return an array of every repeated country?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
1)
var isIntersection =countries1.Intersect(countries2).Any();
2)
var intersectedCountries =countries1.Intersect(countries2);
1)
var isIntersection = countries1.Intersect(countries2).Any();
2)
var intersectedCountries = countries1.Intersect(countries2);
对于国家 1 和 2 之间的交集:
countries1.Intersect(countries2).ToArray()
For intersection between countries 1 and 2:
countries1.Intersect(countries2).ToArray()
阿迪尔森的回答涵盖了您的问题 #2 和问题 #1
您会这样做:
.Any()
将在匹配的第一个实例上返回 true,而.Count()
或.ToArray()
> 将迭代整个列表。Adilson's answer covers your question #2, and for question #1
You would do:
The
.Any()
will return true on the first instance of a match, whereas.Count()
or.ToArray()
will iterate the entire list.使用 LINQ:
但是,这不会考虑字符串大小写等。您可能想要做的是将一个快速
IEqualityComparer
组合在一起:然后将其与您的
Intersect 一起传递调用:
With LINQ:
But, this doesn't take into consideration string casing etc. What you may want to do, is chuck together a quick
IEqualityComparer<string>
:Then pass that in with your
Intersect
call: