开发者

Better way to return the value from a property from a child object when the childobject can be null

开发者 https://www.devze.com 2023-04-09 19:51 出处:网络
I try to explain this with an example: public class Player { public string FirstName {get; set;} public Team Team {get; set;}

I try to explain this with an example:

public class Player
{
    public string FirstName {get; set;}
    public Team Team {get; set;}
}

public class Team
{
    public string Name {get; set;}
}

Now I want to map a Player to a PlayerVM (ViewModel)

public class PlayerVM
{
    public string PlayerFirstName {get; set;}

    public string TeamName {get; set;}
}

So the code is something like:

public List<PlayerVM> GetPlayers()
{
    // Lazy loading enabled,
    // so the Team child objects (if present, will be retrieved)
    var players = Database.GetPlayers();

    var list = new List<PlayerVM>();
    foreach (var player in players)
    {
        var vm = new PlayerVM();

        vm.PlayerFirstName = player.FirstName;

        if (player.Team != null)
        {
            vm.TeamName = player.Team.Name;
        }
        else
        {
            vm.TeamName = "-- no team --";
        }

        list.Add(vm);
    }

    return list;
}

I want to replace

if (player.Team != null)
{
    vm.TeamName = player.Team.Name;
}
else
{
    vm.TeamName = "-- no team --";
}

by something like:

vm.TeamName = Utils.GetProperty<Player>(p => p.Team.Name, "--开发者_如何学JAVA no team --");

is this possible using generic Lamba / Func expressions ?

<< Edit >>

Thanks for the answers, I know I can use oneliners, but I was actually looking for a generic way to access nested child objects. (The nesting could be X levels deep...)

string countryName = Utils.GetProperty<Player>(p => p.Team.Country.Name, "-- no country --");

How to do this ?

<< Edit 2 >> A possible solution would to convert the Func Expression using this code http://code.google.com/p/gim-projects/source/browse/presentations/CantDanceTheLambda/src/MemberNameParser.cs

to a string like "Team.Country.Name".

Then use reflection to access the properties.


What about

vm.TeamName = p.Team.Name != null ? p.Team.Name : "-- no team --";

No generics, no lambda, but if you want to replace the if/else block with a oneliner, this is the way to go.

So to clean up the entire mapping it will be

list.Add( new PlayerVM{
            PlayerFirstName = player.FirstName,    
            TeamName = player.Team.Name != null ? player.Team.Name : "-- no team --"
         });  


I would create a property in the Player class:

public string TeamName {
    get {
        return this.Team != null ? this.Team.Name : "-- no team --";
    }
}


A possible solution can be found here:

Get Nested Property value using reflection and Linq.Expression

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号