c# numeric类型在集合中的使用技巧

avatar
作者
猴君
阅读量:0

在C#中,System.Numerics命名空间提供了一些数值类型,如BigIntegerComplex等。这些类型可以在集合中使用,但需要注意一些技巧和最佳实践。

  1. 使用List<T>HashSet<T>存储BigInteger
using System.Numerics; using System.Collections.Generic;  var bigIntegers = new List<BigInteger> { BigInteger.Parse("12345678901234567890"), BigInteger.Parse("98765432109876543210") };  // 或者使用HashSet来存储不重复的BigInteger var uniqueBigIntegers = new HashSet<BigInteger> { BigInteger.Parse("12345678901234567890"), BigInteger.Parse("98765432109876543210") }; 
  1. 使用Dictionary<TKey, TValue>存储Complex
using System.Numerics; using System.Collections.Generic;  var complexNumbers = new Dictionary<string, Complex> {     { "A", new Complex(1, 2) },     { "B", new Complex(3, 4) } }; 
  1. 使用LINQ查询Numeric类型集合:
using System.Linq; using System.Numerics; using System.Collections.Generic;  var bigIntegers = new List<BigInteger> { BigInteger.Parse("12345678901234567890"), BigInteger.Parse("98765432109876543210") };  // 查询大于100的BigInteger var result = bigIntegers.Where(x => x > BigInteger.Parse("100")); 
  1. 使用SortedSet<T>Numeric类型进行排序:
using System.Numerics; using System.Collections.Generic;  var bigIntegers = new SortedSet<BigInteger> { BigInteger.Parse("12345678901234567890"), BigInteger.Parse("98765432109876543210") };  foreach (var number in bigIntegers) {     Console.WriteLine(number); } 
  1. 使用BinarySearchList<T>中查找Numeric类型:
using System.Numerics; using System.Collections.Generic;  var bigIntegers = new List<BigInteger> { BigInteger.Parse("12345678901234567890"), BigInteger.Parse("98765432109876543210") }; bigIntegers.Sort(); // 先对列表进行排序  int index = bigIntegers.BinarySearch(BigInteger.Parse("12345678901234567890")); if (index >= 0) {     Console.WriteLine($"Found at index: {index}"); } else {     Console.WriteLine("Not found"); } 

总之,在C#中使用Numeric类型集合时,需要注意集合的初始化、元素的添加和删除、查询和排序等操作。同时,根据实际需求选择合适的集合类型,如List<T>HashSet<T>Dictionary<TKey, TValue>等。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!