Asp.Net C#4.0新特性:distinct去掉集合重复数据

Asp.Net C# 4.0中用distinct去掉集合重复数据(非SQL),Distinct大家都知道干嘛的,常用于SQL查询时去掉重复数据。非常好用吧。嘿嘿,那么如果是集合中的重复数据怎么办呢?只能费尽心思想办法循环、遍历检测。下面我介绍一个 C# 4.0 中一个方法,对值进行比较返回序列中的非重复元素。


C# 4.0 中 Distinct 语法
public static IEnumerable<TSource> Distinct<TSource>(   
this IEnumerable<TSource> source  
)
C# 4.0 中 Distinct Demo
protected void Page_Load(object sender, EventArgs e)  
{      
List<String> strMaoBlogList = new List<String>();      
strMaoBlogList.Add("a");      
strMaoBlogList.Add("a");      
strMaoBlogList.Add("b");      
strMaoBlogList.Add("b");      
strMaoBlogList.Add("c");      
strMaoBlogList.Add("c");        
String _maoBlog = String.Empty;      
IEnumerable<String> distinctList = strMaoBlogList.Distinct();      
foreach (String str in distinctList)          
_maoBlog += str + " ";        
Response.Write(_maoBlog.Trim());  
}
MSDN 示例
List<int> ages = new List<int> 
{ 21, 46, 46, 55, 17, 21, 55, 55 };  
IEnumerable<int> distinctAges = ages.Distinct();  
outputBlock.Text += "Distinct ages:" + "\n";  foreach (int age in distinctAges)  
{     
outputBlock.Text += age + "\n";  
}  
/*   
This code produces the following output:   Distinct ages:   21   46   55   17  
*/
原文地址:https://www.cnblogs.com/zxjyuan/p/2084053.html