我有两个数据来源说:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
并填充了一些数据:
var data1 = new List<Person>() { new Person() { Id = 1, Name = "data 11" }, new Person() { Id = 2, Name = "data 12" } };
var data2 = new List<Employee>() { new Employee() { Id = 1, Name = "data 21" }, new Employee() { Id = 2, Name = "data 22" }, new Employee() { Id = 3, Name = "data 23" } };
我已创建查询以将Left Join设为:
var query = (from person in (data1)
join employee in (data2) on person.Id equals employee.Id
into temp
from y in temp.DefaultIfEmpty()
select new { Data = y }).ToList();
现在我的问题是: - 我想从源代码制作父母或者#34;&#34;一个数据源具有更高的Count。
场景就像:if data1.Count&gt; data2.Count那么: 与上述查询相同
如果data2.Count&gt; data1.Count那么:
var query = (from employee in (data2)
join person in (data1) on employee.Id equals
person.Id
into temp
from y in temp.DefaultIfEmpty()
select new { Data = y }).ToList();
我怎样才能实现这一目标,因为Linq不提供开箱即用的权利加入Linq? 请指导。
答案 0 :(得分:0)
如果您可以定义两个实体都实现的接口,那么您可以基于此接口一般性地编写查询:
interface INameIdPair {
int Id { get; set; }
string Name { get; set; }
}
public class Person : INameIdPair {
public int Id { get; set; }
public string Name { get; set; }
}
public class Employee : INameIdPair {
public int Id { get; set; }
public string Name { get; set; }
}
var data1 = new List<INameIdPair> {
new Person { Id = 1, Name = "data 11" },
new Person { Id = 2, Name = "data 12" }
};
var data2 = new List<INameIdPair> {
new Employee { Id = 1, Name = "data 21" },
new Employee { Id = 2, Name = "data 22" },
new Employee { Id = 3, Name = "data 23" }
};
var from1 = data1.Count > data2.Count ? data1 : data2;
var from2 = from1 == data1 ? data2 : data1;
var query =
(from ff1 in from1
join ff2 in from2 on ff1.Id equals ff2.Id
into temp
from y in temp.DefaultIfEmpty()
select new {Data = y}
).ToList();