1

I'we got two Lists of my class 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;
}

I need to join them. I used to do it like this:

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);
    }

As you can see, if Ids or NomenCode and ProducerName are equal, for me it's the same Nomen. now my task have changed and I need to take, if they equal, the one with less minPrice. Please, help me to solve this problem. Tried to do the same with linq, but failed

        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();

Mostly because I need to join Lists by Ids OR {NomenCode, ProducerName} and I don't know how to do it.

MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
el_konor
  • 528
  • 1
  • 6
  • 15

2 Answers2

4

Concat, GroupBy and then Select again? for example (less untested than before):

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));
moreON
  • 1,977
  • 17
  • 19
1

Linq joins with OR conditions have been answered in this SO post: Linq - left join on multiple (OR) conditions

In short, as Jon Skeet explains in that post, you should do something like

from a in tablea
from b in tableb
where a.col1 == b.col1 || a.col2 == b.col2
select ...
Community
  • 1
  • 1
Wicher Visser
  • 1,513
  • 12
  • 21
  • In my query was still a problem with correct group by. Firs answer is more close. But thanks anyway. – el_konor Apr 14 '16 at 08:27