排序列表<>何时添加项目?

时间:2018-01-25 16:14:55

标签: c# linq

我目前有一个来自对象的项目列表。我将列表发送到另一个方法,将其复制到csv文件。我遇到的问题是,这些项目按字母顺序列在csv上,而不是按照添加的顺序列出。我有办法保留原始订单吗?

SampleDatalist.Add(new SampleDataViewModel
{
    PlanID = Convert.ToString(allFields["AdditionalInfo-PlanDetails-planNumber"]),
    SSN = Convert.ToString(allFields["AccountOwnerInfo-ContactInfo-ssn"]),
    EmployeeNumber = "",
    DivisionId = "",
    FirstName = Convert.ToString(allFields["AccountOwnerInfo-ContactInfo-firstName"]),
    MiddleName = "",
    LastName = Convert.ToString(allFields["AccountOwnerInfo-ContactInfo-lastName"]),
    StreetAddress = Convert.ToString(allFields["AccountOwnerInfo-ContactInfo-homeAddress1"]),
    City = Convert.ToString(allFields["AccountOwnerInfo-ContactInfo-homeCity"]),
    State = Convert.ToString(allFields["AccountOwnerInfo-ContactInfo-homeState"]),
    PostalCode = Convert.ToString(allFields["AccountOwnerInfo-ContactInfo-homeZip"]),
    HomePhone = Convert.ToString(allFields["AccountOwnerInfo-ContactInfo-homePhone"]),
    OfficePhone = Convert.ToString(allFields["AccountOwnerInfo-ContactInfo-businessPhone"]),
    Email = Convert.ToString(allFields["AccountOwnerInfo-ContactInfo-email"]),
    DateOfBirth = Convert.ToString(allFields["AccountOwnerInfo-ContactInfo-dob"]),
    DateOfHire = Convert.ToString(allFields["AdditionalInfo-PlanDetails-dateOfHire"]),
    MaritalStatus = Convert.ToString(allFields["AdditionalInfo-PlanDetails-maritalStatus"])
});

WriteCSV(PCSDatalist, @"C:\Users\brand\Documents\New_PPT_" + dt + ".csv");



public void WriteCSV<T>(IEnumerable<T> items, string path)
{
    Type itemType = typeof(T);
    var props = itemType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                        .OrderBy(p => p.Name);

    using (var writer = new StreamWriter(path, true))
    {
        foreach (var item in items)
        {
            writer.WriteLine(string.Join(", ", props.Select(p => p.GetValue(item, null))));
        }
    }
}

1 个答案:

答案 0 :(得分:1)

从您显示的代码中,列表中的项目按照添加顺序编写。

但是,每个项目的属性将按字母顺序书写 - 因为您明确要求它们是:.OrderBy(p => p.Name)。如果你不这样做,删除那个子句,属性将按照它们在类中定义的顺序编写。