我希望找到一种更好的方法(可能有一个很好的
linq表达式)将像“41,42x,43”这样的字符串列表转换为有效long的列表.下面的代码有效,但感觉很难看.
string addressBookEntryIds = "41,43"; var ids = addressBookEntryIds.Split(new[] {',',';'},StringSplitOptions.RemoveEmptyEntries); var addressBookEntryIdList =new List<long>(); foreach (var rec in ids) { long val; if (Int64.TryParse(rec,out val)) { addressBookEntryIdList.Add(val); } }
解决方法
string addressBookEntryIds = "41,43"; Func<string,long?> safeParse = (s) => { long val; if (Int64.TryParse(s,out val)) { return val; } return null; }; var longs = (from s in addressBookEntryIds.Split(new[] {',StringSplitOptions.RemoveEmptyEntries) let cand = safeParse(s) where cand.HasValue select cand.Value).ToList();