list与数组转Hashset&SortedSet
//创建hashset去重 var hashSet = new HashSet<int>(){1,1,2,2}; Console.WriteLine("HashSet:"+String.Join(", ", hashSet)); // HashSet:1, 2 //创建list包含重复元素 var ints = new List<int>{1,1,3,3,2,2}; //创建数组转HashSe包含重复元素 int[] numbers = { 1, 1, 3, 2, 2 }; //list转HashSet var set = ints.ToHashSet(); Console.WriteLine("List转HashSet:"+String.Join(", ", set)); //List转HashSet:1, 3, 2 var immutableSortedSet = ints.ToImmutableSortedSet(); Console.WriteLine("immutableSortedSet:"+String.Join(", ", immutableSortedSet)); //数组转HashSet var hashSet1 = new HashSet<int>(numbers); Console.WriteLine("数组转HashSet:"+String.Join(", ", hashSet1)); //数组转HashSet:1, 3, 2 //数组转SortedSet var sortedSet = new SortedSet<int>(numbers); Console.WriteLine("数组转SortedSet:"+String.Join(", ", sortedSet)); //数组转SortedSet:1, 2, 3
当hashset存的是类时
创建饮料类
public class Drink { public String Name { get; set; } public int Price { get; set; } }
new一个HashSet存放饮料类
var drinks = new HashSet<Drink>(); drinks.Add(new Drink{Name = "牛奶",Price = 19}); drinks.Add(new Drink{Name = "牛奶",Price = 20}); drinks.Add(new Drink{Name = "茉莉花茶",Price = 19}); drinks.Add(new Drink{Name = "茉莉花茶",Price = 19}); foreach (var drink in drinks) { Console.WriteLine(drink.Name+drink.Price); }
打印出来并未去重
自定义比较规则
public class DrinkEquelityCompare : IEqualityComparer<Drink> { public bool Equals(Drink x, Drink y) { //Name相等去除 return x.Name == y.Name; } public int GetHashCode(Drink obj) { return base.GetHashCode(); } }
重新new一个类
//var drinks = new HashSet<Drink>(new DrinkEquelityCompare()); drinks.Add(new Drink{Name = "牛奶",Price = 19}); drinks.Add(new Drink{Name = "牛奶",Price = 20}); drinks.Add(new Drink{Name = "茉莉花茶",Price = 19}); drinks.Add(new Drink{Name = "茉莉花茶",Price = 19}); foreach (var drink in drinks) { Console.WriteLine(drink.Name+drink.Price); }
此时打印以及去除掉Name相同的值了
SortedSet存放类时自定义排序规则
还是用刚刚的Drink类
public class DrinkCompare : IComparer<Drink> { public int Compare(Drink x, Drink y) { //返回值>0 x大; 返回值=0,一样大; 返回值小于0,y大 return x.Price-y.Price; } }
添加数据
SortedSet<Drink> sorted = new(new DrinkCompare()); sorted.Add(new Drink{Name = "橘汁",Price = 19}); sorted.Add(new Drink{Name = "牛奶",Price = 20}); sorted.Add(new Drink{Name = "茉莉花茶",Price = 17}); sorted.Add(new Drink{Name = "可乐",Price = 21}); foreach (var drink in sorted) { Console.WriteLine(drink.Name+drink.Price); }
打印出来的数据以及按照price进行排序了