温馨提示×

如何在C#中将List转为其他集合

c#
小樊
322
2024-06-28 20:31:27
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C#中,可以通过以下几种方法将List转为其他集合:

  1. 使用ToList()方法将List转为新的List集合:
List<int> list = new List<int> { 1, 2, 3, 4, 5 };
List<int> newList = list.ToList();
  1. 使用ToArray()方法将List转为数组:
List<int> list = new List<int> { 1, 2, 3, 4, 5 };
int[] array = list.ToArray();
  1. 使用ToDictionary()方法将List转为字典集合:
List<KeyValuePair<int, string>> list = new List<KeyValuePair<int, string>> { 
    new KeyValuePair<int, string>(1, "One"),
    new KeyValuePair<int, string>(2, "Two"),
    new KeyValuePair<int, string>(3, "Three")
};
Dictionary<int, string> dictionary = list.ToDictionary(x => x.Key, x => x.Value);
  1. 使用ToHashSet()方法将List转为HashSet集合:
List<int> list = new List<int> { 1, 2, 3, 4, 5 };
HashSet<int> hashSet = list.ToHashSet();

这些方法可以根据具体需求选择合适的集合类型来转换List。

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

推荐阅读:如何在java中将数组转为list集合

0