linq查询组在一个字符串列表中

use*_*681 4 c# linq generics

我对cq的linq查询很新.我有一个字符串列表,我想获得一个新列表或删除所有双字符串.

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());
Run Code Online (Sandbox Code Playgroud)

无法隐式转换 'System.collection.Generic.IEnumarable<System.Collections.Generic.List<string>''System.collections.Generic.List<string>.存在显式转换(您是否错过了演员?)

Wil*_*ore 10

您还可以在LINQ中使用distinct关键字:

var dedupedlist = zipcodes.Distinct().ToList();
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅https://msdn.microsoft.com/en-us/library/vstudio/bb348436(v=vs.100).aspx


fub*_*ubo 5

这是删除重复值的最有效方法

var groupbyzipcodes = new HashSet<string>(zipcodes);
Run Code Online (Sandbox Code Playgroud)

我已经讨论过这个问题(HashSetVS Distinct()在这里

  • 有趣的是,我认为可以以最有效的方式实现与众不同。我个人认为,distinct更具可读性,但这取决于应用程序的性能要求。 (2认同)