如何在List中转换var?

Ale*_*967 0 c# struct var

我需要将var类型转换为List<myStruct>。我不得不用来var订购列表,myStruct我得到了orderedList2,但是现在我需要迭代该列表,但我不知道该怎么做。

public struct myStruct
{

    public String delivery;
    public String articleCode;
    public String dex;
    public String phase;
    public String quantity;

};

List<myStruct> myList;

var orderedList2 = myList.OrderByDescending(x =>
    {
        DateTime dt;
        DateTime.TryParse(x.delivery, out dt);
        return x;
    });

// now I have to fill the ListView again
foreach(myStruct str in orderedList2)
{
    string[] s = new string[5];
    s[0] = str.delivery;
    s[1] = str.articleCode;
    s[2] = str.dex;
    s[3] = str.phase;
    s[4] = str.quantity;

    ListViewItem itl = new ListViewItem(s);
    ////String s = r["DEXART"].ToString();
    ////MessageBox.Show(s);
    listView1.Items.Add(itl);
}
Run Code Online (Sandbox Code Playgroud)

当代码命中该foreach语句时,我得到一个异常。

Raf*_*fal 6

在您的结构上实现IComparable,或者您的订单lambda错误:

 var orderedList2 = myList.OrderByDescending(x =>
    {
        DateTime dt;
       if( DateTime.TryParse(x.delivery, out dt))
           return dt;
        return DateTime.MinValue;
    });
Run Code Online (Sandbox Code Playgroud)

您可以按照.ToList()cal进行获取List<myStruct> orderedList2


有用:

在此处输入图片说明