How to define conditional fields in anonymous types

If you are familiar with Linq you probably know what anonymous types are. I don't want to speak about anonymous types in this article I only want to show you something which I think can be very useful in some circumstances.

Whenever you define an anonymous type you can define some fields for it , sometimes you probably want to define a field which is dependant on the result of one or some other fields ( It is the problem that I had once I was using anonymous types and I found how to do that and now I'm going to show you) :

Suppose you have a collection called Football Players where each Football Player is defined as follow:

namespace FootballPlayers
{
    class FootballPlayer
   
    {
        public string Name { get; set; }
        public string Position { get; set; }
        public string SportClub { get; set; }
    }
}

For example you want to select all Football Players from your collection who play for Real Madrid and write Name and Position for each player and if the player's Name is Raul then he is captain.

For this we  can write:

var players = new List<Player>() { new Player { Name = "Ronaldinho", Position = "Forward", SportClub = "Milan" }, new Player { Name = "Raul", Position = "Forward", SportClub = "Realmadrid" }, new Player { Name = "casillas", Position = "GoalKeeper", SportClub = "Realmadrid" } };

    var q = from a in players

        where a.SportClub == "Realmadrid"
       
select new { Name = a.Name, Position = (a.Name == "Raul" ? a.Position + " (C)" : a.Position) };

foreach
(var item in q)

{
    Console.WriteLine(item.Name + " : " + item.Position);
}

Hope it can help you in your different projects.


Similar Articles