1

My simplified data structure is as follows::

FieldA    FieldB
abc        
abc
abc        emailabc
abc        emailabc
def        
def
def
ijk
ijk        emailijk
abc        emailabc1
abc        emailabc1

My required output::

FieldA    FieldB
abc        emailabc
def
ijk        emailijk
abc        emailabc1

How do I get this result.. I tried doing a groupby but that gave out duplicate fieldA without feildB as well.

Any help is sincerely appreciated.

Arnab
  • 2,324
  • 6
  • 36
  • 60

2 Answers2

2

This LINQ query should take care of it, even when there are multiple entries with non-empty FieldB:

 var result =
     from item in items
     group item by item.FieldA into grp
     let nonEmpty =
         from g in grp
         where !String.IsNullOrEmpty(g.FieldB)
         select g
     from subItem in nonEmpty.Any() ? nonEmpty : grp
     group subItem by new { subItem. FieldA, subItem.FieldB } into subGrp
     select subGrp.First();
Sefe
  • 13,731
  • 5
  • 42
  • 55
1

You can use

var list = YourModel.GroupBy(x =>x.FieldA)
                    .Select(x => new
                    {
                        FieldA = x.Key,
                        FieldB = x.Max(y=>y.FieldB)
                    }).ToList();

with two columns

var list = YourModel.GroupBy(x =>x.FieldA)
                .Select(x => new
                {
                    FieldA = x.Key,
                    FieldB = x.Max(y=>y.FieldB)
                }).GroupBy(x => new { x.FieldA, x.FieldB })
                 .Select(x => new
                 {
                     FieldA = x.Key.FieldA,
                     FieldB = x.Key.FieldB
                 }).ToList();