在C#中检查List的索引超出异常

时间:2017-05-19 19:24:09

标签: linq c#-4.0

如何检查列表的索引异常。我在下面尝试了但仍然没有抛出索引异常。

LstOfItems.Where(p => p.LstOfSubItems[i] != null)

2 个答案:

答案 0 :(得分:0)

LstOfItems.Where(p => p.LstOfSubItems.Count > i)

如果p.LstOfSubItems.[i]超出界限,简单地执行i将抛出异常。

答案 1 :(得分:0)

很难说你在尝试什么,但我认为你想要这样的东西:

% original list
list = {'01-Sep-1882','01-Aug-1895','04/01/1912','Tue, 05/28/46','Tue, 03/10/53','06/20/58','Thu, 09/20/73','Fri, 08/15/75','Sun, 12/01/1996'}

% split each cell in the list
list_split = cellfun(@(x) strsplit(x,' '), list, 'UniformOutput', false);

% now detect where there is unusual format, this will give logical array
abnormal_idx = cellfun(@(x) length(x) == 2, list_split,'UniformOutput', true)

% make copy
clean_list = list;

% now at abnormal indices retain only the part that MATLAB understands
clean_list(abnormal_idx) = cellfun(@(x) x{2}, list_split(abnormal_idx), 'UniformOutput', false);

% now run datenum on clean list
date_num = cellfun(@datenum, clean_list, 'UniformOutput', true);