I have designed Types as follow:
class Cricket
{
string type;
Team tm;
public Team Team
{
get { return tm; }
set { tm = value; }
}
public string Type
{
get { return type; }
set { type = value; }
}
}
class Team
{
string country;
Players plr;
public Players Players
{
get {return plr; }
set { plr = value; }
}
public string Country
{
get { return country; }
set { country = value; }
}
}
class Players
{
string name;
DateTime dob;
int run;
public string Name
{
get { return name; }
set { name = value; }
}
public DateTime DOB
{
get { return dob; }
set { dob = value; }
}
public int Run
{
get { return run; }
set { run = value; }
}
}
I have to get the following using LINQ techniques.
1) Youngest all data of the youngest player among all teams
2) Oldest Player of each team
3) The highest run scorer will r开发者_开发知识库eceive Gold Medal,rest of the players of all team will receive Silver medal. (Please look at the GetPlayer() i have declared var Medal=new String[] {"Gold","Silver"} to associate the Medal )
public void GetPlayer()
{
var TeamMatrix = new Cricket[]
{
new Cricket{ Type="Twenty20", Team=new Team{ Country="England",
Players=new Players{ DOB=Convert.ToDateTime("01/Jan/1989"),
Name="Russel", Run=45}}},
new Cricket{ Type="Twenty20", Team=new Team{ Country="England",
Players=new Players{ DOB=Convert.ToDateTime("01/Jan/1991"),
Name="Joel", Run=56}}},
new Cricket{ Type="Twenty20", Team=new Team{ Country="Australia",
Players=new Players{ DOB=Convert.ToDateTime("01/Jan/1990"),
Name="Clark", Run=145}}},
new Cricket{ Type="Twenty20", Team=new Team{ Country="Australia",
Players=new Players{ DOB=Convert.ToDateTime("01/Jan/1971"),
Name="Bevan", Run=156}}}
};
var Medal = new string[] { "Gold", "Silver" };
var tm = (from mat in TeamMatrix select new { mat.Team.Players.DOB }).Max();
Console.WriteLine("Youngest Age={0}",tm);
}
When I declare
var tm = (from mat in TeamMatrix select new { mat.Team.Players.DOB }).Max();
I receive error
atleast one object must implement IComparable.
What is the actual way to complete the above three tasks? ( Tasks 1 ,2 ,3 are explained above).
Thanks to all.
The error you receive is because the anonymous class you declare is not comparable. You need to compare the DOB property:
var tm = (from mat in TeamMatrix
select new { mat.Team.Players.DOB }).Max(mat => mat.DOB);
What this does is select the DOB
property of the anonymous class as the property to be compared.
Alternatively, and much simpler, is:
var tm = (from mat in TeamMatrix select mat.Team.Players.DOB).Max();
Since really, there is no need for an anonymous class (unless you're trying to retrieve multiple properties at once, like a player's DOB and Name).
Hopefully that helps you.
精彩评论