How do I Iterate a List<T> in C#

David Gray 176 Reputation points
2024-01-03T11:00:21.36+00:00

Hi,

How can I iterate through a List<T> in a generic method? In the sandbox example below I don't have the class properties available in either of the foreach loops.

Also get an error if I try to use the correct type instead of var in the foreach line,

Do I need to cast the List<T> as a concrete type of List?

Thanks

void Main()
{
	var listOfCars = new Car().GetCars();
	var listOfCartoons = new Cartoon().GetCartoons();
	
	ShowLists(listOfCars);
	ShowLists(listOfCartoons);
}

public static void ShowLists<T>(List<T> list)
{
	Type t = list.GetType();

	if (t == typeof(List<Car>))
	{
		foreach (var c in list)
		{
			Console.WriteLine(c.);
		}
	}
	else
	{
		foreach (Cartoon c in list)
		{
			Console.WriteLine(c.);
		}
	}
}

public class Car
{
	public string Manufacturer { get; set; }
	public string Model { get; set; }
	public string Country { get; set; }
	
	public List<Car> GetCars()
	{
		var cars = new List<Car>();
		cars.Add(new Car() { Manufacturer = "VW", Model = "Phaeton", Country = "Germany" });
		cars.Add(new Car() { Manufacturer = "Land Rover", Model = "Range Rover Sport", Country = "UK" });
		return cars;
	}
}

public class Cartoon
{
	public string Title { get; set; }
	
	public List<Cartoon> GetCartoons()
	{
		var cartoons = new List<Cartoon>();
		cartoons.Add(new Cartoon() { Title = "Family Guy" });
		cartoons.Add(new Cartoon() { Title = "Americaan Dad" });
		return cartoons;
	}
}
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2024-01-03T12:57:30.48+00:00

    Hi @David Gray , Welcome to Microsoft Q&A,

    In C#, generic methods cannot identify the actual types of type parameters at compile time, so it is not feasible to use list.GetType() directly inside a generic method to determine the generic type. For your scenario, one possible approach is to use the is keyword to check the type of each element and then perform the appropriate operation. The specific code is as follows:

    void Main()
    {
        var listOfCars = new Car().GetCars();
        var listOfCartoons = new Cartoon().GetCartoons();
    
        ShowLists(listOfCars);
        ShowLists(listOfCartoons);
    }
    
    public static void ShowLists<T>(List<T> list)
    {
        foreach (var item in list)
        {
            if (item is Car car)
            {
                Console.WriteLine($"Car: {car.Manufacturer}, {car.Model}, {car.Country}");
            }
            else if (item is Cartoon cartoon)
            {
                Console.WriteLine($"Cartoon: {cartoon.Title}");
            }
        }
    }
    
    public class Car
    {
        public string Manufacturer { get; set; }
        public string Model { get; set; }
        public string Country { get; set; }
    
        public List<Car> GetCars()
        {
            var cars = new List<Car>();
            cars.Add(new Car() { Manufacturer = "VW", Model = "Phaeton", Country = "Germany" });
            cars.Add(new Car() { Manufacturer = "Land Rover", Model = "Range Rover Sport", Country = "UK" });
            return cars;
        }
    }
    
    public class Cartoon
    {
        public string Title { get; set; }
    
        public List<Cartoon> GetCartoons()
        {
            var cartoons = new List<Cartoon>();
            cartoons.Add(new Cartoon() { Title = "Family Guy" });
            cartoons.Add(new Cartoon() { Title = "Americaan Dad" });
            return cartoons;
        }
    }
    

    User's image

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2024-01-03T15:37:33.62+00:00

    Use NuGet package ObjectDumper.NET for this. Below show two different styles for displaying your data.

    Full source

    namespace DumpingApp;
    
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.Title = "Dump";
            var listOfCars = new Car().GetCars();
            var listOfCartoons = new Cartoon().GetCartoons();
    
            Console.WriteLine(ObjectDumper.Dump(listOfCars));
            Console.WriteLine();
            Console.WriteLine(ObjectDumper.Dump(listOfCartoons, DumpStyle.CSharp));
            Console.ReadLine();
        }
    }
    public class Car
    {
        public string Manufacturer { get; set; }
        public string Model { get; set; }
        public string Country { get; set; }
    
        public List<Car> GetCars()
        {
            var cars = new List<Car>();
            cars.Add(new Car() { Manufacturer = "VW", Model = "Phaeton", Country = "Germany" });
            cars.Add(new Car() { Manufacturer = "Land Rover", Model = "Range Rover Sport", Country = "UK" });
            return cars;
        }
    }
    
    public class Cartoon
    {
        public string Title { get; set; }
    
        public List<Cartoon> GetCartoons()
        {
            var cartoons = new List<Cartoon>();
            cartoons.Add(new Cartoon() { Title = "Family Guy" });
            cartoons.Add(new Cartoon() { Title = "Americaan Dad" });
            return cartoons;
        }
    }
    

    Dump1

    1 person found this answer helpful.

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.