2017-06-02 28 views
1

我有一個Func<IList<string>>我想要分配給一個屬性。返回三元組內的lambda

我想檢查列表中是否有任何內容,如果有,那麼我想在開始時插入一個項目,然後返回列表。

如果沒有我只想返回一個列表。

看來我能做到這一點,如:

Errors = new Func<IList<string>>(() => 
       { 
        if (errors.Any()) 
        { 
         errors.Insert(0, $"{tp.Name}"); 
         return errors; 
        } 
        else 
        { 
         return null; 
        } 

       })(), 

有沒有一種方法,我可以用一個三元做到這一點?或者一個整潔的方式?與三元我不能做像List.Insert(T),因爲它返回無效,而不是列表。

乾杯

回答

0

你可以寫一個extension method

public static class ListExtensions { 
    public static InsertAndReturnSelf<T>(this List<T> source, T item){ 
     source.Insert(0, item); 
     return source; 
    } 
} 

那麼你可以做

Errors = errors.Any() ? errors.InsertAndReturnSelf($"{testCastStep.Name}") : null; 

當然,如果標準庫有這將是很好的更fluent interface

0

你是對的,插入一個項目到一個列表返回void,而不是名單。你可以做什麼,是返回一個新的名單,而不是:

var existinglist = new List<string> { "three", "one", "five" }; 

var condition = true; 

var resultList = condition ? new[] { "owl" }.Concat(existinglist).ToList() : existinglist;