Reputation: 935
When creating objects like:
var customers = new Customers
{
Persons = new List<Person>
{
new Person { CustomId = "111" },
new Person { CustomId = "222" }
},
Organizations = new List<Organization>
{
new Organization { CustomId = "333" }
},
Keys = new HashSet<string> { "111", "222", "333" }
};
I want to change the initialization of Keys to use the previous value from Person[0].CustomId, Person[1].CustomId and Organization[0].CustomId. (Not hardcoded like this "111", "222", "333")
Is there a simple way to do this inside this type of initialization? I can add the keys after the initialization of customers like this:
foreach (var person in customers.Persons)
{
customers.Keys.Add(person.CustomId);
}
foreach (var org in customers.Organizations)
{
customers.Keys.Add(org.CustomId);
}
But I cannot create Keys from Person and Organization properties in the same initialization as customers?
Upvotes: 0
Views: 93
Reputation: 1738
Make Keys into a public property like:
public HashSet<string> Keys
{
get
{
// create and return a new hashset from persons and organizations
}
}
This way you newer have to think about updating your Keys member.
Upvotes: 0
Reputation: 151720
You can create the collections first, and concatenate the selected keys:
var persons = new List<Person>
{
new Person { CustomId = "111" },
new Person { CustomId = "222" }
};
var organizations = new List<Organization>
{
new Organization { CustomId = "333" }
};
var keys = persons.Select(p => p.CustomId)
.Concat(organizations.Select(o => o.CustomId));
var customers = new Customers
{
Persons = persons,
Organizations = organizations,
Keys = new HashSet<string>(keys),
}
But like others said, there's more issues with this implementation. Do you want to use this syntax for every consumer of the Customers class? How will you keep the key collection up to date with the Persons and Organizations collections, like when you add or remove items from them?
public class Customers
{
public List<Person> Persons { get; set; }
public List<Organization> Organizations { get; set; }
public Customers()
{
Persons = new List<Person>();
Organizations = new List<Organization>();
}
public Customers(IEnumerable<Person> persons,
IEnumerable<Organization> organizations)
: this()
{
Persons.AddRange(persons);
Organizations.AddRange(organizations);
}
public IEnumerable<string> Keys
{
return Persons.Select(p => p.CustomId)
.Concat(Organizations.Select(o => o.CustomId));
}
}
Then a call site may look like this:
var persons = new List<Person>
{
new Person { CustomId = "111" },
new Person { CustomId = "222" }
};
var organizations = new List<Organization>
{
new Organization { CustomId = "333" }
};
var customers = new Customers(persons, organizations);
var keys = customers.Keys;
Upvotes: 5