温馨提示×

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

c#
小樊
86
2024-06-28 20:31:27
栏目: 编程语言

在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。

0