1

(Simplified)

I have a list of full name Strings. The first 6 characters are the first name always.

List<string>()
  fredXXsmith
  aliceXFloor
  billXXjohnson
  fredXXperterson

How can I get the list of unique first names from these strings in LINQ?

  fredXX 
  aliceX 
  billXX
Ian Vink
  • 66,960
  • 104
  • 341
  • 555
  • This might be a bit old, but it could still be useful: [http://stackoverflow.com/a/1300116/1026130](http://stackoverflow.com/a/1300116/1026130) –  Mar 12 '13 at 19:45

3 Answers3

4

You just need to project the full names to the substrings, and then use Distinct:

var firstNames = names.Select(x => x.Substring(0, 6))
                      .Distinct();

This is assuming (given your example) that you always have at least 6 characters (padded with X). Add a ToList call to the end of the chain if you want a List<string>.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
3
names.Select(fullName => fullName.Substring(0, 6)).Distinct();

Substring gets you the first six characters, and Distinct gives you unique results.

Bort
  • 7,398
  • 3
  • 33
  • 48
2
names.Select(x => x.Substring(0,6)).Distinct()
Khan
  • 17,904
  • 5
  • 47
  • 59