如何在C#中将列表内Stylist对象的指定变量输出到控制台?
Got it, let's walk through how to output the properties of your Stylist objects from the list to the console. First, I’ll assume your Stylist class is defined with the public properties you’re using (since it’s not included in your code snippet):
public class Stylist { public string FirstName { get; set; } public string LastName { get; set; } public string Phone { get; set; } public string Email { get; set; } public string Rate { get; set; } }
Now, here are a few practical ways to output the data:
1. Output All Specified Properties for Every Stylist
Use a foreach loop to iterate over each Stylist in your list, then print out each property you care about. This is the most straightforward approach:
// Finish building your list first stylists.Add(stylist1); stylists.Add(stylist2); // Iterate and output each property foreach (var stylist in stylists) { Console.WriteLine($"First Name: {stylist.FirstName}"); Console.WriteLine($"Last Name: {stylist.LastName}"); Console.WriteLine($"Phone: {stylist.Phone}"); Console.WriteLine($"Email: {stylist.Email}"); Console.WriteLine($"Rate: {stylist.Rate}"); Console.WriteLine("---"); // Add a separator for readability }
This will print each stylist's full details with a clear divider between entries.
2. Output a Single Specific Property
If you only need to print one particular property (e.g., just all email addresses), simplify the loop to focus on that:
Console.WriteLine("All Stylist Emails:"); foreach (var stylist in stylists) { Console.WriteLine($"- {stylist.Email}"); }
3. Concise Single-Line Output per Stylist
For a cleaner, more compact view, combine all properties into one line using string interpolation:
foreach (var stylist in stylists) { Console.WriteLine($"{stylist.FirstName} {stylist.LastName} | Phone: {stylist.Phone} | Email: {stylist.Email} | Rate: {stylist.Rate}"); }
Bonus: Filter with LINQ Before Outputting (Optional)
If you want to output only specific stylists (e.g., those with a rate over 200), use LINQ to filter the list first:
using System.Linq; // Don't forget to add this namespace at the top var highRateStylists = stylists.Where(s => int.Parse(s.Rate) > 200); foreach (var stylist in highRateStylists) { Console.WriteLine($"High-rate Stylist: {stylist.FirstName} {stylist.LastName} (Rate: {stylist.Rate})"); }
Note: Make sure to handle potential parsing errors if Rate might not be a valid integer!
内容的提问来源于stack exchange,提问作者Rhys Hudspeth

