6

I am very new to linq query with c#. I have a list of strings and I would like to get a new list or delete all double strings.

List<string> zipcodes = new List<string>();
zipcodes.Add("1234");
zipcodes.Add("1234");
zipcodes.Add("1234");
zipcodes.Add("4321");
zipcodes.Add("4321");

List<string> groupbyzipcodes =
(from zip in zipcodes
group zip by zip into newgroup
select newgroup.ToList());

cannot implicitly convert type 'System.collection.Generic.IEnumarable<System.Collections.Generic.List<string>' to 'System.collections.Generic.List<string>. an explicit conversion exists (are you missing a cast?)

dcastro
  • 66,540
  • 21
  • 145
  • 155
user3432681
  • 564
  • 4
  • 10
  • 25

5 Answers5

13

You can also use the distinct keyword in LINQ:

var dedupedlist = zipcodes.Distinct().ToList();

For more see https://msdn.microsoft.com/en-us/library/vstudio/bb348436(v=vs.100).aspx

William Moore
  • 3,844
  • 3
  • 23
  • 41
5

this is the most efficient way to remove duplicate values

var groupbyzipcodes = new HashSet<string>(zipcodes);

I already discussed that issue (HashSet vs Distinct()) here

Community
  • 1
  • 1
fubo
  • 44,811
  • 17
  • 103
  • 137
  • An interesting read: https://stackoverflow.com/questions/6298679/whats-better-for-creating-distinct-data-structures-hashset-or-linqs-distinct – William Moore Jul 30 '15 at 08:16
  • 2
    Interesting, I would have thought that distinct would have been implemented in the most efficient way. Personally I feel that distinct is more readable, but it depends on the performance requirements of the application. – William Moore Jul 30 '15 at 08:20
2

There is a dedicated Linq method for this purpose:

var newList = zipCodes.Distinct().ToList();

https://msdn.microsoft.com/en-us/library/vstudio/bb348436(v=vs.100).aspx

w.b
  • 11,026
  • 5
  • 30
  • 49
2

If you only have a list of strings you can use distinct()

zipcodes.Distinct();

It will give you the uniq values of the list

Rgds

Marcus Höglund
  • 16,172
  • 11
  • 47
  • 69
2

As others have answered - there exists Distinct to get a distinct list from an IEnumerable<T>.

Your specific problem was that you have a ToList() inside the brackets, and it should be outside.

List<string> groupbyzipcodes =
(from zip in zipcodes
group zip by zip into newgroup
select newgroup.ToList())

should have been

List<string> groupbyzipcodes =
(from zip in zipcodes
group zip by zip into newgroup
select newgroup.Key).ToList();
Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • 1
    Try running this code and you'll get `Cannot implicitly convert type 'System.Collections.Generic.List>' to 'System.Collections.Generic.List'`. You need to do `select newgroup.Key` to get this working. – Chris Jul 30 '15 at 08:28
  • @Chris - thanks, good spot. – Jamiec Jul 30 '15 at 08:32