-1

I'm looking for a LINQ function that returns a list of unique strings from a list of objects which contain these strings. The strings of the objects are not unique. Like this:

List before:

name="abc",value=3
name="xyz",value=5
name="abc",value=9
name="hgf",value=0

List this function would return:

"abc","xyz","hgf"

Does such a function even exist? Of course I know how I could implement this manually, but I was curious if LINQ can do this for me.

AyCe
  • 664
  • 2
  • 9
  • 28

3 Answers3

3
var foo = list.Select(p => p.name).Distinct().ToList();
Jan Köhler
  • 5,425
  • 3
  • 28
  • 33
2

You could use the Distinct extension method. So basically you will first project the original objects into a collection of strings and then apply the Distinct method:

string[] result = source.Select(x => x.name).Distinct().ToArray();
Darin Dimitrov
  • 994,864
  • 265
  • 3,241
  • 2,902
0
(from object in objectList
 select object.name).Distinct();
Mohamad Shiralizadeh
  • 7,733
  • 5
  • 59
  • 85
Thair
  • 171
  • 6