从C#list获取对象初始化语法

时间:2016-10-19 22:31:33

标签: c# .net c#-4.0 reflection

我有一个类型员工列表。

public class Employee
    {
        public string Name { get; set; }
        public int Id { get; set; }
        public string Level { get; set; }
    }

List<Employee> empList = new List<Employee>();

假设此列表中有10个项目,从此列表中,我想生成对象初始化代码。所以基本上我应该得到这样的字符串:

    "Employee e = new Employee{Name: "A", Id:1, Level:1};
    Employee e = new Employee{Name: "B", Id:2, Level:2};
    Employee e = new Employee{Name: "C", Id:3, Level:1};
Employee e = new Employee{Name: "D", Id:4, Level:6};
    Employee e = new Employee{Name: "E", Id:5, Level:2};
    Employee e = new Employee{Name: "F", Id:6, Level:5}
Employee e = new Employee{Name: "G", Id:7, Level:4};
    Employee e = new Employee{Name: "H", Id:8, Level:3};
    Employee e = new Employee{Name: "I", Id:9, Level:1};
Employee e = new Employee{Name: "J", Id:10, Level:1}";

我这样做的原因是,我从数据库获取记录列表,但它没有排序顺序(另一个属性)。我需要手动为每个项目添加排序顺序(硬编码)。 因此,如果我不自动执行此操作,我将拥有的唯一其他选项将要求我手动创建对象(而不是从数据库中获取值)并将SortOrder属性添加到每个对象。

1 个答案:

答案 0 :(得分:1)

我不明白如何让这段代码对你有所帮助,但这里是:

String.Join(
    Environment.NewLine,
    empList.Select(x =>
        $"Employee e = new Employee() {{ Name = \"{x.Name}\", Id = {x.Id}, Level = \"{x.Level}\" }};"));

我建议你有一个更好的选择是创建一个排序字典,创建手动排序顺序,然后用它来排序你从数据库加载的列表。

做这样的事情:

var sorter = new Dictionary<int, string>()
{
    { 1, "c" },
    { 2, "a" },
    { 3, "b" },
    { 4, "c" },
    { 5, "c" },
    { 6, "a" },
    { 7, "a" },
    { 8, "b" },
    { 9, "d" },
    { 10, "c" },
};

empList =
    empList
        .OrderBy(e => sorter.ContainsKey(e.Id) ? sorter[e.Id] : "z")
        .ToList();