C# List<T>常用操作

1、List<T>之间的转换

((List<object>)sourceList).Select(n => (T)n).ToList();

2、DataTable中的某一列转为List<T>

(from r in dataTable.AsEnumerable() select r.Field<string>("datname")).ToList<string>();
(from r in dataTable.AsEnumerable() select r.Field<int>("fid")).ToList<int>()  

3、List获取最后一个元素(单个)

string str = lst[lst.Length-1];

切片语法糖:string str = lst[^1];

4、List获取元素第一到第三的元素

var temp = new string[] { lst[1], lst[2], lst[3] };
var temp = lst.Skip(1).Take(3).ToArray();
切片语法糖:var temp = lst[1..4];

5、List中的某一列转为逗号分割的string

List<long> ids = new List<long> { 1, 2, 3 };
string str = string.Join(",", ids.Select(q => "'" + q + "'"));

6、List转为Dictionary

List<RegularFileInfo> _RegularFilesList;
List<RegularFolderInfo> _RegularFolderList;
new Dictionary<string, List<RegularFileInfo>> tempDic = _RegularFolderList.ToDictionary(key => key.FolderName, 
FieldsTable => _RegularFilesList.FindAll(n => n.FolderName == FieldsTable.FolderName));

7、获取两个List的重复元素

List<string> repeatList = shpfileldsList.Where(p => list.Any(p2 => p.ToLower() == p2)).ToList();

8、

posted @ 2021-10-28 15:32  白草红叶黄花  阅读(1021)  评论(0编辑  收藏  举报