2017-06-02 43 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;