我有两个班级名单Nomen:
var N1 = new List<Nomen>();
var N2 = new List<Nomen>();
public class Nomen
{
public string Id;
public string NomenCode;
...
public string ProducerName;
public decimal? minPrice;
}
我需要加入他们。我曾经这样做过:
result = N2.Union(N1, new NomenComparer()).ToList();
class NomenComparer : IEqualityComparer<Nomen>
{
public bool Equals(Nomen x, Nomen y)
{
return x.Equals(y);
}
public int GetHashCode(Nomen nomen)
{
return nomen.GetHashCode();
}
}
public override int GetHashCode()
{
return (Id + NomenCode + ProducerName).GetHashCode();
}
public bool Equals(Nomen n)
{
if (!String.IsNullOrEmpty(Id) && Id == n.Id) return true;
return (NomenCode == n.NomenCode && ProducerName == n.ProducerName);
}
正如您所看到的,如果Ids或NomenCode和ProducerName相同,对我而言,它是相同的Nomen。 现在我的任务已经改变了,如果它们相等,我需要采取较少minPrice的任务。请帮我解决这个问题。 试图用linq做同样的事,但失败了
var groups = (from n1 in N1
join n2 in N2
on new { n1.Id, n1.NomenCode, n1.ProducerName } equals new { n2.Id, n2.NomenCode, n2.ProducerName }
group new { n1, n2 } by new { n1.Id, n1.NomenCode, n1.ProducerName } into q
select new Nomen()
{
NomenCode = q.Key.NomenCode,
ProducerName = q.Key.ProducerName,
minPrice = q.Min(item => item.minPrice)
}).ToList();
主要是因为我需要加入Ids或{NomenCode,ProducerName}列表,我不知道该怎么做。
答案 0 :(得分:4)
Concat,GroupBy然后再次选择?例如(比以前更少未经测试):
var nomens = N1.Concat(N2)
.GroupBy(n=>n, new NomenComparer())
.Select(group=>group.Aggregate( (min,n) => min == null || (n.minPrice ?? Decimal.MaxValue) < min.minPrice ? n : min));
答案 1 :(得分:1)
Linq加入OR条件已在此SO帖子中得到解答: Linq - left join on multiple (OR) conditions
简而言之,正如Jon Skeet在那篇文章中解释的那样,你应该做一些像
这样的事情from a in tablea
from b in tableb
where a.col1 == b.col1 || a.col2 == b.col2
select ...