首页 > 解决方案 > Fill complex object property List based on string.split condition

问题描述

I have a complex object and need to fill the data based on split condition that I get from reader. Below object need to filter data based on "--" ( Example given below).

Class Employee {
    public string fName {get;} {set;}
    public List<string> Departments {get;} {set;}
}

once I get the data from reader, I am looping and one of the column Department has value like {"Sales -- Payroll -- HR"}

while (dr.read())
{
    new Employee() {
        fname = dr["name],
            Departments = new List<string>
            {
                dr["Department"].ToString().Split(
                    new string[] {" -- "}, 
                    StringSplitOptions.None).ToString()
            }
    } 
}

I tried above option but still not getting desired results.. I need 3 string array based on above example part of Departments property.

Any idea what I am missing?

标签: c#list

解决方案


I think you mean to use the RemoveEmptyEntries + to make the result as ToList() and assigned it.

Departments = dr["Department"].ToString().Split(new string[] {"--"}, StringSplitOptions.RemoveEmptyEntries).ToList()

In you're example you tried to make a Splitted array ToString() which will give you a string representation of an object (and not an actual list object) and then you tried to put it in a list.

Instead, i've splitted the result into a list and assign it directly to Departments and not to new List<string>.


推荐阅读