温馨提示×

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

c#
小樊
101
2024-08-28 16:57:12
栏目: 编程语言
开发者测试专用服务器限时活动,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>等。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:c#中numeric类型有哪些

0