今天群里有同学问如何用linq取结果集的行号,查了一下资料,发现linq有很简单的方法可以实现,花了几分钟写了一个测试用例,现记录下来,以备参考:
/// <summary>
/// 测试类
/// </summary>
public class models
{
public int id { set; get; }
public string Name { set; get; }
public string Phone { set; get; }
public string Address { set; get; }
public DateTime Birthday { set; get; }
private static int idx { set; get; } = 0;
public models()
{
id = idx++;
Name = "testName" + id.ToString();
Phone = "testPhone" + id.ToString();
Address = "testAddress" + id.ToString();
Birthday = DateTime.Now.AddHours(id);
} }
下面是实现方法:
var list = new List<models>();
list.Add(new models());
list.Add(new models());
list.Add(new models());
list.Add(new models());
list.Add(new models());
list.Add(new models());
var tt = list.OrderBy(p => p.Name).OrderByDescending(p =>p.Birthday).OrderByDescending(p => p.id).Select((p, idx) => new {
row = idx,
name = p.Name,
phone = p.Phone
});