从列表中删除重复项<;字符串>;在C#中
本文关键字:字符串 lt gt 列表 删除 | 更新日期: 2023-09-27 18:22:07
从C#中的列表中删除重复项
我有一个数据读取器来读取数据库中的字符串。
我使用列表来聚合从数据库读取的字符串,但这个字符串中有重复的字符串。
有没有人能在C#中快速从泛型列表中删除重复项的方法?
List<string> colorList = new List<string>();
public class Lists
{
static void Main()
{
List<string> colorList = new List<string>();
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
colorList.Add(variableFromDB.ToString());
foreach (string color in colorList)
{
Response.Write(color.ToString().Trim());
}
}
}
colorList = colorList.Distinct().ToList();
foreach (string color in colorList.Distinct())
IEnumerable<Foo> distinctList = sourceList.DistinctBy(x => x.FooName);
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector)
{
var knownKeys = new HashSet<TKey>();
return source.Where(element => knownKeys.Add(keySelector(element)));
}
使用LINQ:
var distinctItems = colorList.Distinct();
类似的帖子:使用linq