for (int i = 0; i < li2.Count; i++) //外循环是循环的次数
{
for (int j = li2.Count - 1 ; j > i; j--) //内循环是 外循环一次比较的次数
{
if (li2[i] == li2[j])
{
li2.RemoveAt(j);
}
}
}
去掉modelList中title重复的内容,不区分大小写
class Program { static void Main(string[] args) { List<Model> modelList = new List<Model>() { new Model() { ID = 1, Title = "abcde" }, new Model() { ID = 2, Title = "ABCDE" }, new Model(){ ID = 3, Title = "AbcdE" }, new Model() { ID = 4, Title = "A" }, new Model() { ID = 5, Title = "a" } }; Console.Read(); } } public class Model { public int ID { get; set; } public string Title { get; set; } }
解决方案一:这里比较的前提是对象的哈希代码相等。否则不会比较,因为哈希代码不相等。两个对象显然不相等
//定义一个类继承IEqualityComparer接口 public class ModelComparer : IEqualityComparer<Model> { public bool Equals(Model x, Model y) { return x.Title.ToUpper() == y.Title.ToUpper(); } public int GetHashCode(Model obj) { return obj.Title.ToUpper().GetHashCode(); } }
modelList = modelList.Distinct(new ModelComparer()).ToList();
解决方案二:
var title = modelList.GroupBy(m => m.Title.ToLower().Trim()).Select(m => new { ID = m.FirstOrDefault().ID }); modelList = modelList.Where(m => title.Select(mo => mo.ID).Contains(m.ID)).ToList(); foreach (var item in modelList) { Console.WriteLine(item.ID + " " + item.Title); }