如标题所述,在ASP.NET应用程序开发中,两个集合做比较时 我们使用微软IEnumerable封装的 Except/Intersect/Union 取 差集/交集/并集 方法是非常的方便的;
但以上对于不太熟悉的小伙伴来讲,在遇到求包含引用类型(不包含string)集合时就非常的苦恼;
下面我将带着大家去了解如何通过微软自带方法方式去取**复杂类型集合**的差集、交集、并集。
这里是场景,我有以下两个学生集合。
namespace Test2
{
internal class Program
{
public void Main()
{
//列表1
List<Student> StudentList1 = new List<Student>()
{
new Student {Id=1,Name="小明",Age=27 },
new Student {Id=3,Name="大郭",Age=28 },
new Student {Id=4,Name="老登",Age=29 }
};
List<Student> StudentList2 = new List<Student>()
{
new Student {Id=1,Name="小明",Age=27 },
new Student {Id=3,Name="大郭",Age=28 },
new Student {Id=4,Name="老登",Age=29 },
new Student {Id=4,Name="小路",Age=28 },
new Student {Id=4,Name="小明",Age=30 }
};
}
}
}
生成两个实体集合;
完整调用示例(.NET Core):
namespace Test2
{
internal class Program
{
public static void Main()
{
//列表1
List<Student> StudentList1 = new List<Student>()
{
new Student {Id=1,Name="小明",Age=27 },
new Student {Id=2,Name="大郭",Age=28 },
new Student {Id=3,Name="老登",Age=29 }
};
//列表2
List<Student> StudentList2 = new List<Student>()
{
new Student {Id=1,Name="小明",Age=27 },
new Student {Id=2,Name="大郭",Age=28 },
new Student {Id=3,Name="老登",Age=29 },
new Student {Id=4,Name="小路",Age=28 },
new Student {Id=5,Name="小明",Age=30 }
};
//取比列表1里多出来的学生数据 并输出
var ExceptData = StudentList2.Except(StudentList1);
Console.WriteLine("差集:" + String.Join(";", ExceptData.Select(x => { return $"{x.Id}-{x.Name}-{x.Age}"; })));
//取列表1与列表2里共有的学生数据
var IntersectData = StudentList1.Intersect(StudentList2);
Console.WriteLine("交集:" + String.Join(";", IntersectData.Select(x => { return $"{x.Id}-{x.Name}-{x.Age}"; })));
//获取办理所有学生的数据(一个相同的学生只能一条)
var UnionData = StudentList1.Union(StudentList2);
Console.WriteLine("并集:"+String.Join(";", UnionData.Select(x => { return $"{x.Id}-{x.Name}-{x.Age}"; })));
}
}
}
输出:
差集:1-小明-27;2-大郭-28;3-老登-29;4-小路-28;5-小明-30
交集:null
并集:1-小明-27;2-大郭-28;3-老登-29;1-小明-27;2-大郭-28;3-老登-29;4-小路-28;5-小明-30
正常我们声明的类
/// <summary>
/// 学生类
/// </summary>
internal class Student
{
/// <summary>
/// 编号
/// </summary>
public int Id { get; set; }
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 年龄
/// </summary>
public int Age { get; set; }
}
因为我们要对比的是引用类型,因为在对比除string引用类型外,其他引用类型的对比默认都是对比的堆里地址,所以我们要实现一个自定义的对比方案
我们需要继承一个接口 IEqualityComparer<T> 泛型接口
如下:(这里我们以年龄与名做为对比条件)
/// <summary>
/// 学生类
/// </summary>
internal class Student : IEqualityComparer<Student>
{
/// <summary>
/// 编号
/// </summary>
public int Id { get; set; }
/// <summary>
/// 姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 年龄
/// </summary>
public int Age { get; set; }
/// <summary>
/// 比较器
/// </summary>
/// <param name="s1">比较实体1</param>
/// <param name="s2">比较实体2</param>
/// <returns></returns>
public bool Equals(Student s1, Student s2)
{
//验证相等条件
if (s1.Name == s2.Name && s1.Age == s2.Age)
{
return true;
}
return false;
}
/// <summary>
/// 获取唯一条件
/// </summary>
/// <param name="stu"></param>
/// <returns></returns>
public int GetHashCode(Student stu)
{
return (stu.Name + "|" + stu.Age).GetHashCode();
}
}
修改了类后还有最重要的一点:就是修改比较的方法(相当于声明一个自定义的比较器给方法)
//取比列表1里多出来的学生数据 并输出
var ExceptData = StudentList2.Except(StudentList1,new Student());
Console.WriteLine("差集:" + String.Join(";", ExceptData.Select(x => { return $"{x.Id}-{x.Name}-{x.Age}"; })));
//取列表1与列表2里共有的学生数据
var IntersectData = StudentList1.Intersect(StudentList2,new Student());
Console.WriteLine("交集:" + String.Join(";", IntersectData.Select(x => { return $"{x.Id}-{x.Name}-{x.Age}"; })));
//获取办理所有学生的数据(一个相同的学生只能一条)
var UnionData = StudentList1.Union(StudentList2,new Student());
Console.WriteLine("并集:"+String.Join(";", UnionData.Select(x => { return $"{x.Id}-{x.Name}-{x.Age}"; })));
输出:
差集:4-小路-28;5-小明-30
交集:1-小明-27;2-大郭-28;3-老登-29
并集:1-小明-27;2-大郭-28;3-老登-29;4-小路-28;5-小明-30
到这里引用类型的比较已经完成了,比较器的条件方法可以根据需求调整,如有不足之处,希望大家多多指正!!!
作为我的Rails应用程序的一部分,我编写了一个小导入程序,它从我们的LDAP系统中吸取数据并将其塞入一个用户表中。不幸的是,与LDAP相关的代码在遍历我们的32K用户时泄漏了大量内存,我一直无法弄清楚如何解决这个问题。这个问题似乎在某种程度上与LDAP库有关,因为当我删除对LDAP内容的调用时,内存使用情况会很好地稳定下来。此外,不断增加的对象是Net::BER::BerIdentifiedString和Net::BER::BerIdentifiedArray,它们都是LDAP库的一部分。当我运行导入时,内存使用量最终达到超过1GB的峰值。如果问题存在,我需要找到一些方法来更正我的代
是的,我知道最好使用webmock,但我想知道如何在RSpec中模拟此方法:defmethod_to_testurl=URI.parseurireq=Net::HTTP::Post.newurl.pathres=Net::HTTP.start(url.host,url.port)do|http|http.requestreq,foo:1endresend这是RSpec:let(:uri){'http://example.com'}specify'HTTPcall'dohttp=mock:httpNet::HTTP.stub!(:start).and_yieldhttphttp.shou
我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串
我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)
有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳
我正在尝试解析一个CSV文件并使用SQL命令自动为其创建一个表。CSV中的第一行给出了列标题。但我需要推断每个列的类型。Ruby中是否有任何函数可以找到每个字段中内容的类型。例如,CSV行:"12012","Test","1233.22","12:21:22","10/10/2009"应该产生像这样的类型['integer','string','float','time','date']谢谢! 最佳答案 require'time'defto_something(str)if(num=Integer(str)rescueFloat(s
我正在玩HTML5视频并且在ERB中有以下片段:mp4视频从在我的开发环境中运行的服务器很好地流式传输到chrome。然而firefox显示带有海报图像的视频播放器,但带有一个大X。问题似乎是mongrel不确定ogv扩展的mime类型,并且只返回text/plain,如curl所示:$curl-Ihttp://0.0.0.0:3000/pr6.ogvHTTP/1.1200OKConnection:closeDate:Mon,19Apr201012:33:50GMTLast-Modified:Sun,18Apr201012:46:07GMTContent-Type:text/plain
我目前正在使用以下方法获取页面的源代码:Net::HTTP.get(URI.parse(page.url))我还想获取HTTP状态,而无需发出第二个请求。有没有办法用另一种方法做到这一点?我一直在查看文档,但似乎找不到我要找的东西。 最佳答案 在我看来,除非您需要一些真正的低级访问或控制,否则最好使用Ruby的内置Open::URI模块:require'open-uri'io=open('http://www.example.org/')#=>#body=io.read[0,50]#=>"["200","OK"]io.base_ur
1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里
//1.验证返回状态码是否是200pm.test("Statuscodeis200",function(){pm.response.to.have.status(200);});//2.验证返回body内是否含有某个值pm.test("Bodymatchesstring",function(){pm.expect(pm.response.text()).to.include("string_you_want_to_search");});//3.验证某个返回值是否是100pm.test("Yourtestname",function(){varjsonData=pm.response.json