使用 LINQ 合并 C# 中的两个对象列表
我有两个 List
,它们都是相同的类型。有没有一种简单的方法可以合并到两个集合,而无需循环遍历两个集合并将它们合并到第三个集合中?
代码
var myObject= new List<Core.MyObject>();
var myObject2= new List<Core.MyObject>();
if(!string.IsNullOrEmpty(txb.Text))
{
var repository = ServiceLocator.Current.GetInstance<Core.RepositoryInterfaces.IRepository>();
myObject= repository.GetWherePostCodeLike(txb.Text).ToList();
}
if(!string.IsNullOrWhiteSpace(ddl.SelectedValue))
{
var repository = ServiceLocator.Current.GetInstance<Core.RepositoryInterfaces.IRepository>();
myObject2= repository.GetNearTownX(ddlLocations.SelectedValue).ToList();
}
如果能够在第二个上使用 += 那就太好了,但是这是不允许的......有什么想法吗?
I have two List<T>
s which are both the same type. Is there an easy way to merge to the two sets without looping though both sets and merging them into a third?
Code
var myObject= new List<Core.MyObject>();
var myObject2= new List<Core.MyObject>();
if(!string.IsNullOrEmpty(txb.Text))
{
var repository = ServiceLocator.Current.GetInstance<Core.RepositoryInterfaces.IRepository>();
myObject= repository.GetWherePostCodeLike(txb.Text).ToList();
}
if(!string.IsNullOrWhiteSpace(ddl.SelectedValue))
{
var repository = ServiceLocator.Current.GetInstance<Core.RepositoryInterfaces.IRepository>();
myObject2= repository.GetNearTownX(ddlLocations.SelectedValue).ToList();
}
It would have been nice to able able to just use the += on the second, but this is not allowed... Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
调用
Concat
(保留重复项)或Union
(跳过重复项)LINQ 方法要使用
Union
,您需要重写Equals
和GetHashCode
按值比较对象。 (或传递IEqualityComparer
)Call the
Concat
(keeps duplicates) orUnion
(skips duplicates) LINQ methodsTo use
Union
, you'll need to overrideEquals
andGetHashCode
to compare objects by value. (or pass anIEqualityComparer<MyObject>
)你有几种选择。
您可以将它们连接起来:
您可以将一个添加到另一个:
You got several alternatives.
You can concatenate them:
You can add one to the other:
你可以这样做:
You can do something like: