Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linq query group by in a list of strings [duplicate]

Tags:

c#

linq

generics

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?)

like image 740
user3432681 Avatar asked Jul 30 '15 08:07

user3432681


2 Answers

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

like image 54
William Moore Avatar answered Nov 11 '22 19:11

William Moore


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

like image 5
fubo Avatar answered Nov 11 '22 19:11

fubo