I have an SQL database with data on walking statistics.
I am extracting the data from SQL into C# into a List of "Transaction". Transaction is a class that represents the amount of kilometers walked by some person during some day i.e.
public class Transaction
{
public Transaction(string firstName, string lastName, DateTime date, int kilomtersWalked)
{
FirstName = firstName;
LastName = lastName;
Date = date;
KilometersWalked = kilomtersWalked;
}
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime Date { get; set; }
public int KilometersWalked { get; set; }
}
I populate the list from SQL, but to illustrate the data I will instantiate it with hardcoded values here.
List<Transaction> transactions = new List<Transaction>
{
new Transaction("Michael", "Smith", new DateTime(2021, 01, 01), 5),
new Transaction("Michael", "Smith", new DateTime(2021, 01, 02), 8),
new Transaction("Michael", "Smith", new DateTime(2021, 01, 03), 7),
new Transaction("Hillary", "Johnson", new DateTime(2021, 01, 01), 12),
new Transaction("Hillary", "Johnson", new DateTime(2021, 01, 02), 3),
new Transaction("Hillary", "Johnson", new DateTime(2021, 01, 03), 6)
};
I would like to convert the data into a List of "PersonStats". PersonStats is a class that represents the amount of kilometers walked by a specific person, not just on one day, but on every day i.e
public class PersonStats
{
public PersonStats(string firstName, string lastName, DateTime[] dates, int[] kilomtersWalked)
{
FirstName = firstName;
LastName = lastName;
Dates = dates;
KilometersWalked = kilomtersWalked;
}
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime[] Dates { get; set; }
public int[] KilometersWalked { get; set; }
}
Although I put a lot of effort into it, I still haven't been able to come up with an elegant way of doing this. Any ideas would be highly appreciated!
CodePudding user response:
You can create instances of PersonStats
by grouping on the FirstName and LastName. It would be better to introduce a unique ID for each person and group by that instead since there are plenty of Michael Smiths in the world.
var ps = transactions
.GroupBy(g => new { g.FirstName, g.LastName })
.Select(g => new PersonStats(
g.Key.FirstName,
g.Key.LastName,
g.Select(_ => _.Date).ToArray(),
g.Select(_ => _.KilometersWalked).ToArray()));