c# - Need help transforming one kind of list into another kind of list using LINQ -
i have list (list<row>) of following row class:
public class row { public list<field> fields { get; } public row() { fields = new list<field>(); } public void addfield(field field) { fields.add(field); } } public class field { public string name { get; } public string value { get; } public field(string name, string value) { this.name = name; this.value = value; } } i want transform list of following format list<document>:
public class document { public string id { get; set; } public string pubid { get; set; } public date date { get; set; } } where "id" incrementing counter , pubid corresponds name: "pubid", value: "somevalue" , date corresponds name: "date", value: "somedate".
i know can done using linq cant wrap head around it!
thanks in advance.
if understand correctly want like
var doclist = rowlist.select((r,i) => new document { id = (i + 1).tostring(), pubid = r.fields.first(f => f.name == "pubid").value, date = datetime.parse(r.fields.first(f => f.name == "date").value) }).tolist(); first off select overload i'm using includes index , assume want first id 1 instead of 0. second use of first going throw exception if not find field specified name (you might consider using firstordefault instead, can problematic "date"). if value "date" field not valid date datetime.parse throw , depending on format might need use datetime.parseexact instead.
Comments
Post a Comment