异常排序c#
本文关键字:排序 异常 | 更新日期: 2023-09-27 18:19:19
当它到达最后一行时,我将低于"索引超出范围"。有谁能帮我找出问题所在吗?
List<string> mailInfoList = new List<string>();
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow row in ds.Tables[0].Rows)
{
string strSubject = row["Subject"].ToString();
string strEmailFrom =row["EmailFrom"].ToString();
string strEmailTo =row["EmailTo"].ToString();
string strEmailCC =row["EmailCc"].ToString();
string strEmailContent=row["EmailContent"].ToString();
string strCreatedOn =row["CreatedOn"].ToString();
mailInfoList.Add(strSubject);
mailInfoList.Add(strEmailFrom);
mailInfoList.Add(strEmailTo);
mailInfoList.Add(strEmailCC);
mailInfoList.Add(strEmailContent);
mailInfoList.Add(strCreatedOn);
var newList = mailInfoList.OrderBy(x => x[1]).ThenBy(x => x[2]).ToList();
}
}
这里。Try thing instead:
var mailInfoList = new List<Tuple<string, string, string, string, string, DateTime>>();
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow row in ds.Tables[0].Rows)
{
string strSubject = row["Subject"].ToString();
string strEmailFrom = row["EmailFrom"].ToString();
string strEmailTo = row["EmailTo"].ToString();
string strEmailCC = row["EmailCc"].ToString();
string strEmailContent = row["EmailContent"].ToString();
// Do proper error handling here
DateTime strCreatedOn = DateTime.Parse(row["CreatedOn"].ToString());
mailInfoList.Add(new Tuple<string, string, string, string, string, DateTime>(
strSubject, strEmailFrom, strEmailTo, strEmailCC, strEmailContent, strCreatedOn
));
var newList = mailInfoList.OrderBy(x => x.Item1).ThenBy(x => x.Item6).ToList();
}
}
它将按主题然后按创建日期对条目进行排序。只要确保DateTime.Parse
不会抛出错误(您也可以使用DateTime.TryParse
请注意,在使用OrderBy(x => x[1])
时,x是指String
类型的mailInfoList
的每个索引,x[1]是指该索引的第二个字符。
那么你确定List的每个索引的长度至少是1吗?
我建议你使用:
var newList = mailInfoList.where( y => y.lenght > 0).OrderBy(x => x[1]).ThenBy(x => x[2]).ToList();
首先,您需要创建类似于数据表对象的类模型,从您的示例中,它看起来像这样,
public class Emails
{
public string Subject { get; set; }
public string EmailFrom { get; set; }
public string EmailTo { get; set; }
public string EmailCc { get; set; }
public string EmailContent { get; set; }
public DateTime CreatedOn { get; set; }
}
和你的更新代码块变成,
List<Emails> mailInfoList = new List<Emails>();
if (ds.Tables[0].Rows.Count > 0)
{
foreach (DataRow row in ds.Tables[0].Rows)
{
Emails email = new Emails();
email.Subject = row["Subject"].ToString();
email.EmailFrom = row["EmailFrom"].ToString();
email.EmailTo = row["EmailTo"].ToString();
email.EmailCc = row["EmailCc"].ToString();
email.EmailContent = row["EmailContent"].ToString();
email.CreatedOn = Convert.ToDateTime(row["CreatedOn"].ToString());
mailInfoList.Add(email);
}
var newList = mailInfoList.OrderBy(c => c.EmailFrom).ThenBy(n => n.CreatedOn);
}