I have a test LINQ list below
List<test> test=new List<test>();
test.Add(new test("Bakery","[email protected]","Donut"));
test.Add(new test("Bakery","[email protected]","Bagel"));
test.Add(new test("Bakery","[email protected]","Cake"));
test.Add(new test("Produce","[email protected]","Apple"));
test.Add(new test("Dairy","[email protected]","Milk"));
test.Add(new test("Dairy","[email protected]","Yogurt"));
Some departments have more than 1 item. How can loop through the list and send 1 email to each department/email address with the item(s). Send 1 email to [email protected] with Donut, Bagel, Cake in the body. Send 1 email to [email protected] with Apple in the body. Send 1 email to [email protected] with Milk, Yogurt in the body
I don't need help with the email part, just need help to loop through the list and get items per department. Thank you very much!!!
CodePudding user response:
I think, you may use the grouping for the task.
var groups = test.GroupBy(x => x.Email);
foreach (var group in groups)
{
var email = group.Key; // Exactly the property from GroupBy
var goods = group.Select(x => x.Good); // Donut, Bagel, Cake...
var body = string.Join(", ", goods);
// Now you can send the email with body containing "Donut, Bagel. Cake"
}
Each instance of the group
variable contains Key
property and the collection of grouped items from the test
collection.
Thus, you can use the group
either with methods like Select
, or with the foreach
operator.
CodePudding user response:
List<test> test=new List<test>();
test.Add(new test("Bakery","[email protected]","Donut"));
test.Add(new test("Bakery","[email protected]","Bagel"));
test.Add(new test("Bakery","[email protected]","Cake"));
test.Add(new test("Produce","[email protected]","Apple"));
test.Add(new test("Dairy","[email protected]","Milk"));
test.Add(new test("Dairy","[email protected]","Yogurt"));
foreach (var group in test.GroupBy(x=> x.Department))
{
var department = group.Key;
var email = group.First().Email;
var body = string.Join(", ", group.Select(x => x.Product));
SendMail(email, department, body);
}