Linq OrderBy Then with Duplicate item

本文关键字:Duplicate item with Then OrderBy Linq | 更新日期: 2023-09-27 18:12:51

我可以在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 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();
    }
}

Linq OrderBy Then with Duplicate item

也许我可以得到它的权利,但为什么你有这个字符串名称参数?你没有使用它。或者你想要得到所有这个名字的记录然后按名字和日期排序?如果你想要这个,那么我认为代码将为你工作:

list.Where(t=> t.Name == name).OrderBy(t => t.Name).ThenBy(t => t.Date).ToList();

另一个问题是你设置了DateTime。在这种情况下,"现在到处都是"的标准不起作用。

如果我错了,请纠正我。我很乐意帮忙

请不要犹豫,使用这个方法。

    list.OrderBy(test => test.Name).ThenBy(test => test.Date).ThenBy(test => test.Id).ToList();