Using Linq to pull from IEnumerable and store in data table

前端 未结 3 1808
天命终不由人
天命终不由人 2021-01-16 05:23

I have a datatable that looks like the following

public static DataTable SetColumnHeaders(DataTable KeyDataTable)
{
    KeyDataTable.Columns.Add(\"First_Name         


        
3条回答
  •  南笙
    南笙 (楼主)
    2021-01-16 05:58

    You can bake your "isInsured" check and your selection of a person into the one query;

    var query = from p in xmlDoc.Elements()
                where ((string)p.Element("InsuredOrPrincipalInfo")
                            .Element("InsuredOrPrincipalRoleCd")) == "Insured"
                select new
                {
                    Firstname = (string)p.Element("GeneralPartyInfo")
                    .Element("NameInfo")
                    .Element("PersonName")
                    .Element("GivenName"),
    
                    LastName = (string)p.Element("GeneralPartyInfo")
                    .Element("NameInfo")
                    .Element("PersonName")
                    .Element("Surname"),
                };
    
    var person = query.FirstOrDefault();
    if (person != null)
    {
        var fileRow = AutoDataTable.NewRow();
        fileRow["First_Name"] = person.Firstname;
        fileRow["Last_name"] = person.LastName;
    }
    

    This isn't super-robust in terms of handling XML in an unexpected format, but it should serve as a good starting point for you. Just fill out the anonymous object initialization with the rest of your elements, casting to the desired types.

提交回复
热议问题