Simmer
Simmer

Reputation: 213

Need help transforming one kind of list into another kind of list using LINQ

I have a list (List<Row>) of the 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 to transform this into a list of the following format List<Document>:

public class Document
{
    public string Id { get; set; }
    public string PubId { get; set; }
    public Date Date { get; set; }
}

Where "Id" is a incrementing counter and PubId corresponds to Name: "PubId", Value: "SomeValue" and Date corresponds to Name: "Date", Value: "SomeDate".

I know that this can be done using LINQ but i just cant wrap my head around it!

Thanks in advance.

Upvotes: 0

Views: 57

Answers (2)

glboothby
glboothby

Reputation: 151

List<Row> rows = GetRows();
int i =0;
List<Document> docs = rows.Select(r => new Document()
{ 
    Id = (i++).ToString(), 
    PubId = r.fields.Where(f => f.Name == "PubId").Select(f => f.Value).FirstOrDefault(), 
    Date = GetDate(r.fields.Where(f => f.Name == "Date").Select(f => f.Value).FirstOrDefault()) 
}).ToList();

public Date GetDate(string input)
{
  // Convert Here.
}

Upvotes: 1

juharr
juharr

Reputation: 32296

If I understand correctly you want something 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 the Select overload I'm using includes the index and I assume you want the first Id to be 1 instead of 0. Second the use of First is going to throw an exception if it does not find a Field with the specified Name (you might consider using FirstOrDefault instead, but that can be problematic for the "Date"). Finally if the Value for the "Date" Field is not a valid date then DateTime.Parse will throw and depending on the format you might need to use DateTime.ParseExact instead.

Upvotes: 3

Related Questions