在C#中,System.Numerics命名空间提供了一些数值类型,如BigInteger、Complex等。这些类型可以在集合中使用,但需要注意一些技巧和最佳实践。
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") };
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) }
};
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"));
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);
}
BinarySearch在List<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>等。