0

I want to get the first one if there are duplicates and discard everything if the name is the same.

Model

var data = [
{id:1, name:"Jay"},{id:2, name:"Jay"}
{id:3, name:"Jay"},{id:4, name:"Jay"} 
]

wish to get

var result =[
{id:1, name:"Jay"}
]
dumb11
  • 129
  • 1
  • 9

1 Answers1

1

You can group them by name and pick a first item out of the group.

var result = data.GroupBy(g => g.Name).Select(g => g.First()).ToList();
Selim Yildiz
  • 5,254
  • 6
  • 18
  • 28
  • Is it guaranteed that the first element of an IGrouping appeared first in the original sequence? – Harald Coppoolse Aug 11 '20 at 06:18
  • Good catch @Harald, According to: https://stackoverflow.com/a/204777/5519709 it should preserve order. – Selim Yildiz Aug 11 '20 at 06:25
  • I got this error with the first keyword System.InvalidOperationException: The LINQ expression '(GroupByShaperExpression: KeySelector: (s.Name), ElementSelector:(EntityShaperExpression: EntityType: Site ValueBufferExpression: (ProjectionBindingExpression: EmptyProjectionMember) IsNullable: False ) – dumb11 Aug 12 '20 at 01:55
  • Did you convert the JSon to object before using that linq? – Selim Yildiz Aug 13 '20 at 05:05