C#:自定义属性的排序列表

时间:2015-09-15 18:05:54

标签: c# sorting

如果这是重复的话我很抱歉。请指出正确的问题。

我有一个名为MyDate的课程,如下所示

public class AccountController : Controller
{
    /// <summary>
    /// Use this method to sign into the website
    /// </summary>
    public void SignIn()
    {
        // Send an OpenID Connect sign-in request.
        if (!Request.IsAuthenticated)
        {
            HttpContext.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" },
                OpenIdConnectAuthenticationDefaults.AuthenticationType);
        }
    }

    /// <summary>
    /// Use this method to sign out of the website
    /// </summary>
    public void SignOut()
    {
        string callbackUrl = Url.Action("SignOutCallback", "Account", routeValues: null, protocol: Request.Url.Scheme);

        Request.GetOwinContext().Authentication.SignOut(
            new AuthenticationProperties { RedirectUri = callbackUrl },
            OpenIdConnectAuthenticationDefaults.AuthenticationType,
            CookieAuthenticationDefaults.AuthenticationType);
    }

    /// <summary>
    /// Use this method to redirect to Home page, once the request has been authenticated
    /// </summary>
    /// <returns>An <see cref="ActionResult"/> object.</returns>
    public ActionResult SignOutCallback()
    {
        if (Request.IsAuthenticated)
        {
            // Redirect to home page if the user is authenticated.
            return RedirectToAction("Index", "Home");
        }

        return View();
    }
}

我的课程名为MyEvent,如下所示

public class MyDate
{
    private SqlDateTime m_dateTime;

    public MyDate(DateTime dateTime)
    {
       if (DateTime.Compare(dateTime, (DateTime)SqlDateTime.MinValue) <= 0)
            m_dateTime = SqlDateTime.MinValue;
        else
            m_dateTime = dateTime;
    }

    public string MMDDYYYYHHMMSS
    {
       get
         {
            if(m_dateTime > SqlDateTime.MinValue)
                return m_dateTime.Value.ToString("MM/dd/yyyy hh:mm:ss tt");
            else
                return String.Empty;
         }
    }
}

我有像MyEvent的集合

public class MyEvent
{
  public int EventId{get;set;}
  public MyDate StartDate{get;set;}
}

现在我需要按StartDate的降序排序myEvents。我遇到的问题是我无法添加IComparable或更改MyDate,因为它是由其他团队编写的,我只是引用dll。我不能控制MyDate代码。任何人都可以帮助我如何做到。我创建了一个新的比较器类,它实现了IComparer但无法理解如何使用它并对myEvents进行排序。

**更新1 **

非常感谢Alexei,Ehsan和Dave帮助我。我尝试了Dave的答案,但它确实奏效了。我试图以更好的方式做到这一点,因此不需要添加任何新属性。我没有尝试使用StringDateComparer的Ehsan方式,但它帮助我理解如何在Order linq语句中使用Comparer。最后,正如阿列克谢指出的那样,我确实喜欢下面的

**更新2 **

有时我为e2.StartDate.MMDDYYYYHHMMSS和/或e2.StartDate.MMDDYYYYHHMMSS获取空字符串,所以我改变了我的代码,如下所示

List<MyEvent> myEvents. 

2 个答案:

答案 0 :(得分:3)

这可能效率低下,但您可以在DateTime类中添加MyEvent属性,将StartDate转换为DateTime并对其进行排序:

public class MyEvent
{
    public int EventId{get;set;}
    public MyDate StartDate{get;set;}
    public DateTime MyStartDate { get { return DateTime.Parse(StartDate.MMDDYYYYHHMMSS); } }
}

var sorted = myEvents.OrderByDescending(e => e.MyStartDate);

或者,您可以使类不可变并在实例化时进行转换:

public class MyEvent
{
    public MyEvent(int eventId, MyDate startDate)
    {
        EventId = eventId;
        StartDate = startDate;
        MyStartDate = DateTime.Parse(StartDate.MMDDYYYYHHMMSS);
    }

    public int EventId{get; private set;}
    public MyDate StartDate{get; private set;}
    public DateTime MyStartDate { get; private set; }
}

答案 1 :(得分:3)

您可以根据需要以这种方式使用Linq OrderyBy()OrderByDescending方法编写它:

var outputDate = myEvents.OrderByDescending(x=>
                          {
                           DateTime parsedDate;
                           return DateTime.TryParseExact(x.StartDate, "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate) ? parsedDate : DateTime.MinValue;
                          });

或正确的方法是为其创建自定义IComparer

public class StringDateComparer : IComparer<string>
{

    public int Compare(string date1, string date2)
    {
        DateTime parsedDate1;
        DateTime.TryParseExact(date1, "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate1);


        DateTime parsedDate2;
        DateTime.TryParseExact(date2, "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out parsedDate2);



        if (parsedDate1 < parsedDate2)
            return -1;
        if (parsedDate1 > parsedDate2)
            return 1;


        return 0;
    }
}

现在调用OrderByDescending()重载,将IComparer个对象作为参数:

var outputDate = myEvents.OrderByDescending(x=>x.StartDate,new StringDateComparer());