简体   繁体   中英

GetValue, How to handle null values into a Linq sentence

I'm having problems exporting an entity to excel.

I have this Linq:

List<PropertyInfo> props = FieldsToExport(EntitySet.AsQueryable());
int iCols = props.Count();

foreach (var Entity in EntitySet)
{
    var values = Enumerable.Range(0, iCols)
        .Select(ii => props[ii].GetValue(Entity)
                                .HandleNullProps()
        );

    // .... write in the sheet
} 

My problem is when the [ii] property of my entity has a null value, it is throwing a null exception even if HandleNullProps() is filtering it..

Here is my HandleNullProps()

public static object HandleNullProps(this object s)
{
    if (s == null)
        return string.Empty;
    else
        return s;
    }
}

if props[ii] is null, then calling GetValue(Entity) will cause a NullReferenceException

your handleNullProps method is not even reached - the exception is thrown before that

update your select to something like this

var values = Enumerable.Range(0, iCols).Select(ii => props[ii] != null ? props[ii].GetValue(Entity) : String.Empty)

and now your handleNullProps method becomes unnecessary.

Edit

Since you're trying Extension Methods, you could use them to get your values anyway like this

var values = Enumerable.Range(0, iCols).Select(ii => props[ii].GetValueOrDefault(Entity))

and let the method be defined like this

public static object GetValueOrDefault(this object s, object entity)
{
    if (s == null)
        return string.Empty;
    else
        return s.GetValue(entity);
    }
}

keep in mind that I put object to both parameters because I don't know they proper types - set the correct types to both parameters and should work fine

the OrDefault part is inspired in one of the linq methods FirstOrDefault

It's not clear what is null in your case.

If it's the Entity then you should filter it out before:

foreach (var Entity in EntitySet.Where(e=>e != null))

If it's the props[ii] then .Select(ii => props[ii]?.GetValue(Entity) should do it.
And You can filter them out after wards the same way as before.
Your code can become:

foreach (var Entity in EntitySet.Where(e => e != null))
{
    var values = Enumerable.Range(0, iCols)
        .Select(ii => props[ii]?.GetValue(Entity)).Where(v => v !=  null);

    // .... write in the sheet
} 

Update: if it's props[ii] then i suggest that you filter it beofre:

List<PropertyInfo> props = FieldsToExport(EntitySet.AsQueryable()).Where(p=>p!=null).ToList();

And the whole code can become simpler anyway:

var values = props.Select(p=>p.GetValue(Entity)).Where(v => v !=  null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM