簡體   English   中英

GetValue,如何將空值處理為Linq語句

[英]GetValue, How to handle null values into a Linq sentence

我在將實體導出到Excel時遇到問題。

我有這個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
} 

我的問題是,當我實體的[ii]屬性具有空值時,即使HandleNullProps()正在對其進行過濾,它也會引發空異常。

這是我的HandleNullProps()

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

如果props[ii]為null,則調用GetValue(Entity)將導致NullReferenceException

您甚至沒有達到handleNullProps方法-在此之前引發異常

更新您的選擇像這樣

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

現在您的handleNullProps方法變得不必要了。

編輯

由於您正在嘗試擴展方法,因此可以像這樣使用它們來獲取您的值

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

並像這樣定義方法

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

請記住,我對兩個參數都放置了object ,因為我不知道它們的正確類型-為兩個參數設置正確的類型並且應該可以正常工作

OrDefault部分是受linq方法之一FirstOrDefault啟發的

目前尚不清楚您的情況是什么。

如果是Entity ,則應在以下條件之前將其過濾掉:

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

如果是props[ii].Select(ii => props[ii]?.GetValue(Entity)應該這樣做。
您也可以像以前一樣在病房之后將其過濾掉。
您的代碼可以變成:

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
} 

更新:如果是props[ii]那么我建議您先過濾它:

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

無論如何,整個代碼可以變得更簡單:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM