C# Linq OrderBy Then带有重复项
我可以在linq中对具有重复值的实体的字符串属性使用OrderBy().Then()。 比如说C# Linq OrderBy Then带有重复项,c#,sql,.net,linq,sql-order-by,C#,Sql,.net,Linq,Sql Order By,我可以在linq中对具有重复值的实体的字符串属性使用OrderBy().Then()。 比如说 public class Test { public Guid Id{get;set;} public string Name{get;set;} public DateTime Date{get;set;} } 我想根据名称(可以重复)对这个测试实体列表进行排序,然后用日期对结果进行排序 比如说 public class Test { public Guid
public class Test
{
public Guid Id{get;set;}
public string Name{get;set;}
public DateTime Date{get;set;}
}
我想根据名称(可以重复)对这个测试实体列表进行排序,然后用日期对结果进行排序
比如说
public class Test
{
public Guid Id { get; set; }
public string Name { get; set; }
public DateTime Date { get; set; }
}
public class TestLinq
{
private IList<Test> list;
public TestLinq()
{
var dateTime = DateTime.Now;
list = new List<Test>
{
new Test {Id = Guid.NewGuid(), Name = "Masoud", Date = dateTime},
new Test {Id = Guid.NewGuid(), Name = "Bahrami", Date = dateTime},
new Test {Id = Guid.NewGuid(), Name = "Ali", Date = DateTime.Now},
new Test {Id = Guid.NewGuid(), Name = "hasan", Date = DateTime.Now},
new Test {Id = Guid.NewGuid(), Name = "Masoud", Date = DateTime.Now},
new Test {Id = Guid.NewGuid(), Name = "Bahrami", Date = DateTime.Now},
};
}
public List<Test> Get(string name)
{
return list.OrderBy(test => test.Name).ThenBy(test => test.Date).ToList();
}
}
公共类测试
{
公共Guid Id{get;set;}
公共字符串名称{get;set;}
公共日期时间日期{get;set;}
}
公共类TestLinq
{
私人名单;
公共TestLinq()
{
var dateTime=dateTime.Now;
列表=新列表
{
新测试{Id=Guid.NewGuid(),Name=“Masoud”,Date=dateTime},
新测试{Id=Guid.NewGuid(),Name=“Bahrami”,Date=dateTime},
新测试{Id=Guid.NewGuid(),Name=“Ali”,Date=DateTime.Now},
新测试{Id=Guid.NewGuid(),Name=“hasan”,Date=DateTime.Now},
新测试{Id=Guid.NewGuid(),Name=“Masoud”,Date=DateTime.Now},
新测试{Id=Guid.NewGuid(),Name=“Bahrami”,Date=DateTime.Now},
};
}
公共列表获取(字符串名称)
{
return list.OrderBy(test=>test.Name).ThenBy(test=>test.Date).ToList();
}
}
也许我能正确地理解它,但是为什么您有这个字符串名参数呢?你没有使用它。或者您想获取所有具有此名称的记录,然后按名称和日期对其进行排序?
如果您需要,那么我认为代码将适用于您:
list.Where(t=> t.Name == name).OrderBy(t => t.Name).ThenBy(t => t.Date).ToList();
另一个问题是您设置了日期时间。在这种情况下,where and then by条件不起作用
如果我在什么地方错了,请纠正我。我很乐意帮忙请不要犹豫,使用这种方法
list.OrderBy(test => test.Name).ThenBy(test => test.Date).ThenBy(test => test.Id).ToList();
是的,您可以,您面临的问题是什么?@Rahul Singh,当运行查询i时出现此错误“order by列表中指定了多次列。order by必须是唯一的”@MasoudBahrami您可以发布整个查询吗,我怀疑您在order by子句中指定了两次Name列?您发布的查询看起来不错。请尝试类似list.OrderBy(test=>test.Name)的操作。然后再尝试(test=>test.Date).ToList();谢谢。是的,name是过滤器的名称,在某些情况下name和Date的值相等。非常感谢,好吧,我很好地测试了它,但我不确定,你的解决方案可以解决它。