我是C#的初学者,有一个问题想请教,我的数据库中有很多名字,我的问题是如何编写脚本来显示没有重复的姓名数据,使用LINQ?
这是一个例子:
string[] names = {hello, hello, stack, stack, overflow, overflow};
我不知道怎么做,能否有人写一个简单的脚本来展示它的实现方式。我可以自己解决剩下的部分。
这是你要的:
string[] names = {"hello", "hello", "stack", "stack", "overflow", "overflow"};
var distinctNames = names.Distinct();
foreach(String distinctName in distinctNames)
Console.WriteLine(distinctName);
names.Distinct().ToList().ForEach( n => Console.WriteLine(n));
string[] names = {"hello", "hello", "stack", "stack", "overflow", "overflow"};
var uniqueNames = (from c in names select c).Distinct();
foreach(String s in uniqueNames) Console.WriteLine(uniqueNames);
var elems = someArray.GroupBy(x => x.PropertyToCompare).Select(y => y.First());
您可以在这里阅读更多内容:http://blog.jordanterrell.com/post/LINQ-Distinct()-does-not-work-as-expected.aspx
var duplicates = suppliers_arr
.GroupBy(i => i)
.Where(g => g.Count() > 1)
.Select(g => g.Key);
if(duplicates.Count() > 0){
foreach (var d in duplicates)
{
ModelState.AddFormError(string.Format("{0} is duplicated",d.ToString()));
}
}else{
//no duplicates
}
.ToList()
。 - Fabian TampToList()
。它显示“'System.Collections.Generic.IEnumerable<string>'不包含定义为'ForEach'的方法,也找不到接受类型为'System.Collections.Generic.IEnumerable<string>'的第一个参数的扩展方法'ForEach'”。 - Kaf