C# - 查找两个 List的公共成员 - Lambda 语法
因此,我编写了这个简单的控制台应用程序来帮助我提问。 在方法的第 3 行使用 lambda 表达式来获取公共成员的正确方法是什么。 尝试了 Join() 但无法找出正确的语法。 作为后续...是否有一种非 LINQ 方法可以在我错过的一行中执行此操作?
class Program
{
static void Main(string[] args)
{
List<int> c = new List<int>() { 1, 2, 3 };
List<int> a = new List<int>() { 5, 3, 2, 4 };
IEnumerable<int> j = c.Union<int>(a);
// just show me the Count
Console.Write(j.ToList<int>().Count.ToString());
}
}
So I wrote this simple console app to aid in my question asking. What is the proper way to use a lambda expression on line 3 of the method to get the common members. Tried a Join() but couldn't figure out the correct syntax. As follow up... is there a non-LINQ way to do this in one line that I missed?
class Program
{
static void Main(string[] args)
{
List<int> c = new List<int>() { 1, 2, 3 };
List<int> a = new List<int>() { 5, 3, 2, 4 };
IEnumerable<int> j = c.Union<int>(a);
// just show me the Count
Console.Write(j.ToList<int>().Count.ToString());
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要
Intersect()
:这是一个基于评论中提到的想法的
OrderedIntersect()
示例。 如果你知道你的序列是有序的,它应该运行得更快 -O(n)
而不是通常的.Intersect()
(不记得我的头顶上) )。 但如果您不知道它们是有序的,它可能根本不会返回正确的结果:You want
Intersect()
:Here's an
OrderedIntersect()
example based on the ideas mentioned in the comments. If you know your sequences are ordered it should run faster —O(n)
rather than whatever.Intersect()
normally is (don't remember off the top of my head). But if you don't know they are ordered, it likely won't return correct results at all:如果您所说的 lambda 语法是指真正的 LINQ 查询,那么它看起来像这样:
lambda 表达式是指当您使用 => 时。 运算符,例如:
您使用 Union 方法所拥有的实际上是一种非 LINQ 方法,但我认为您的意思是一种无需扩展方法的方法。 几乎没有一言以蔽之。 我昨天用字典做了类似的事情。 你可以这样做:
If you by lambda syntax mean a real LINQ query, it looks like this:
A lambda expression is when you use the => operator, like in:
What you have with the Union method really is a non-LINQ way of doing it, but I suppose that you mean a way of doing it without extension methods. There is hardly a one-liner for that. I did something similar using a Dictionary yesterday. You could do like this: