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.
2 Comments
Join the conversation! Your thoughts help the community grow.
Sign in to leave a comment
It is the same account you read, post and publish with — and you will come straight back to this page.

Jhonny Nina VeizagaPosted Feb 24, 2015, 3:55 PM
Great!.
Shahbaz MehmoodPosted Jan 29, 2014, 1:36 PM
That's a good tutorial....very helpful...but there is a slight mistake.i-e,"class FootballPlayer" should be "class Player" b/c we are using "var players = new List<Player>()" Kindly update...thanks.