两个使用Linq的集合比较 [英] Two collection comparision using Linq

查看:71
本文介绍了两个使用Linq的集合比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像
的集合
strnameCollection

i have one collection like
strnameCollection

[0]={number:12, name:"abc"}
[1]={number:13, name:"abc, cdf"}
[2]={number:14, name:"tre"}
[3]={number:15, name:"iuj"}





另一个集合名称如strcollection



one more collection name like strcollection

[0]={number:12, value:"zzzz"}
[1]={number:13, value:"abc, tyu"}





使用LinQ



我需要比较收集和获取匹配记录的数量。例如abc在strnameCollection中匹配并存在2次。



我的结果应该是



USE LinQ

do i need to compare both collection and get count for matching records. example "abc" is matching and existing 2 times in strnameCollection.

My Result should be

{number:12, name:"abc"}
{number:13, name:"abc,cdf"}





i想要使用Linq而不是foreach循环。



i want to make using Linq and not foreach loop.

推荐答案

以下是你的解决方案。



Below is your solution.

var strCollection1 = new[] {
               new{number=12, name="abc"},
               new{number=13, name="abc, cdf"},
               new{number=14, name="tre"},
               new{number=15, name="iuj"}
           };

           var strCollection2 = new[] {
               new{number=12, name="abc"},
               new{number=13, name="abc, cdf"},
           };

           var joined = from x1 in strCollection1
                        join x2 in strCollection2
                           on new { x1.name, x1.number } equals
                              new { x2.name, x2.number }
                        select x1;

           foreach (var item in joined)
           {
               Console.WriteLine("{number=" + item.number + ",name=" + item.name + "}");
           }


这个怎么样:

What about this:
var common = strCollection1.Intersect(strCollection2);
Console.WriteLine(common.Count());



...使用解决方案1中的两个集合。


...using the two collections from Solution 1.


这篇关于两个使用Linq的集合比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆