Malv20
Malv20

Reputation: 159

Access to properties of generic object

I have remote context and I know that classes in this context have the same structure. I want to avoid creating method for each class. Example

public IEnumerable<CommonPersonFeatureValue> GetRegulation()
{
    var query = from c in remoteContext.RegulaminDaneOsobowe
        select new CommonPersonFeatureValue
        {
            PersonId = c.PersonId ?? 0,
            Crated = c.Created ?? DateTime.MinValue,
            CurStatus = String.IsNullOrEmpty(c.CurStatus) ? c.CurStatus : String.Empty,
            NewStatus = String.IsNullOrEmpty(c.NewStatus) ? c.NewStatus : String.Empty,
            Modified = c.Modified ?? DateTime.MinValue
        };

    return query;
}

public IEnumerable<CommonPersonFeatureValue> GetNDA()
{
    var query = from c in remoteContext.NDA
         select new CommonPersonFeatureValue
         {
             PersonId = c.PersonId ?? 0,
             Crated = c.Created ?? DateTime.MinValue,
             CurStatus = String.IsNullOrEmpty(c.CurStatus) ? c.CurStatus : String.Empty,
             NewStatus = String.IsNullOrEmpty(c.NewStatus) ? c.NewStatus : String.Empty,
             Modified = c.Modified ?? DateTime.MinValue
         };

    return query;
}

Is it possible to create method like this

public IEnumerable<CommonPersonFeatureValue> GetCommonPersonFeatureValue<T>(this System.Data.Services.Client.DataServiceQuery<T> items)

The problem is that I don't know how to properly access property of generic object. One solution is use this code

string newStatus = item.GetType().GetProperty("NewStatus").GetValue(item) as string

But I think that it is weak approach. Do you have better solution to replace these two methods in one common method ?

Upvotes: 2

Views: 64

Answers (1)

Ed Chapel
Ed Chapel

Reputation: 6942

If you can make the RegulaminDaneOsobowe and NDA objects implement a common interface (e.g. IThing), then your method take a collection of the interface:

public IEnumerable<CommonPersonFeatureValue> QueryThings<TThing>(IQueryable<TThing> things)
    where TThing : IThing
{
    var query = from c in things
                select new CommonPersonFeatureValue
                {
                    PersonId = c.PersonId ?? 0,
                    Created = c.Created ?? DateTime.MinValue,
                    CurStatus = String.IsNullOrEmpty(c.CurStatus) ? c.CurStatus : String.Empty,
                    NewStatus = String.IsNullOrEmpty(c.NewStatus) ? c.NewStatus : String.Empty,
                    Modified = c.Modified ?? DateTime.MinValue
                };
    return query;
}

This could be called as

var ndaQuery = QueryThings(remoteContext.NDA);
var regulaminDaneOsoboweQuery = QueryThings(remoteContext.RegulaminDaneOsobowe);

Upvotes: 1

Related Questions