I have an array of objects similar to this:
class StateVisitor
{
string FirstName { get; set; }
string LastName { get; set; }
string StateViseted { get; set; }
}
StateVisitor[] StateVisitors = {
new() { FirstName = "Bob", LastName = "Smith", StateViseted = "AL" },
new() { FirstName = "Bob", LastName = "Smith", StateViseted = "AK" },
new() { FirstName = "Bob", LastName = "Jones", StateViseted = "AL" },
new() { FirstName = "Sam", LastName = "Smith", StateViseted = "UT" }
}
And I want to do something like this:
class VisitorsWithCombinedStates {
string FirstName { get; set; }
string LastName { get; set; }
string[] StatesVisetedArray { get; set; }
}
VisitorsWithCombinedStates[] visitorsWithCombinedStates = StateVisitors... /* Linq magic? */
visitorsWithCombinedStates.ForEach(v
=> Console.WriteLine($"{v.FirstName} {v.LastName} visited {string.Join(", ",v.StatesVisitedArray)}"));
// "Bob Smith visited AL, AK"
// "Bob Jones visited AL"
// "Sam Smith visited UT"
Is there an easy way, in C# (probably with LINQ) to flatten that first array into the second array, where it makes an array of the states visited?
CodePudding user response:
You want to group your items by a combination of first and last name and project the result of the grouping as just the state visited
var groups = stateVisitors.GroupBy(sv => new
{
sv.FirstName,
sv.LastName,
},
sv => sv.StateVisited );
Output:
foreach(var g in groups)
{
// g.Key.FirstName
// g.Key.LastName
// g is IEnumerable<string> of visited states
}
CodePudding user response:
An example, to fill your VisitorsWithCombinedStates class:
VisitorsWithCombinedStates[] visitorsWithCombinedStates = StateVisitors.GroupBy(x => new { x.FirstName, x.LastName},x => x.StateViseted)
.Select(x => new VisitorsWithCombinedStates { FirstName = x.Key.FirstName, LastName = x.Key.LastName, StatesVisetedArray = x.ToArray() }).ToArray();
