Linq Grouping and workaround data entry errors in groups

33 views Asked by At

In The Following Table i want to Group by ItemNo & ItemName. For Same ItemNo, ItemName should be typical, but due to data entry errors sometimes they are different : For Item#1 Name should be Name_11 Not ItemName_12. So it creates two groups. In such case for same ItemNo i want to take First ITemName

ItemNo ItemName Other Data
Item#1 Name_11 Other
Item#1 Name_12 Other
Item#2 Name_21 Other

Here is the code that need modification :

var _qry = _models
  .GroupBy(x => new { 
     x.ItemNo, 
     x.ItemName
   })
  .Select(y => new {
     ItemNo   = y.Key.ItemNo,
     ItemName = y.Key.ItemName,
     Other1   = y.Count(x => x.ID != 0),
     Other2   = y.Count(x => x.ID != 0 && (x.Completed == false || x.Completed == null))
   })
  .ToList();
1

There are 1 answers

1
Svyatoslav Danyliv On BEST ANSWER

Remove ItemName from grouping key and get name from first item in the group.

var _qry = _models
  .GroupBy(x => new { 
     x.ItemNo
   })
  .Select(y => new {
     ItemNo   = y.Key.ItemNo,
     ItemName = y.First().ItemName,
     Other1   = y.Count(x => x.ID != 0),
     Other2   = y.Count(x => x.ID != 0 && (x.Completed == false || x.Completed == null))
   })
  .ToList();