使用First()找不到任何内容时,在异常中显示搜索值

时间:2018-02-06 08:14:56

标签: c# linq

First()上执行IEnumerable时,我获得的默认例外是Sequence contains no matching element,但没有搜索到的值。我需要显示搜索到的Id,有没有办法在catch区块中显示Id

public static CustomItem FirstCustom(this IEnumerable<CustomItem> source, Func<CustomItem, bool> predicate)
{
    try
    {
        return source.First(predicate);
    }
    catch (Exception e)
    {
        throw new Exception($"I need to show the searched `Id` here. How to do this? {e.Message}");
    }
}

public class CustomItem
{
    public int Id { get; set; }
}

3 个答案:

答案 0 :(得分:1)

简单的答案:你不能这样做。由于predicate可以是任意函数,例如

(CustomeItem c) => 1 == 2

predicate可能根本不使用任何Id。如果您要搜索Id并在未找到时显示:

public static CustomItem FirstCustom(this IEnumerable<CustomItem> source, int id) { 
  if (null == source)
    throw new ArgumentNullException("source"); // validate public methods' arguments 

  CustomItem result = source.FirstOrDefault(item => item.Id == id);

  if (null == result)
    throw new ArgumentException($"Id {id} has not been found!", "id");
  else
    return result;  
}

答案 1 :(得分:0)

您可以使用表达式实现此目的:

这个怎么样:

 public static CustomItem FirstCustom(this IEnumerable<CustomItem> source, Expression<Func<CustomItem, bool>> predicate)
    {
        BinaryExpression binExpr = null;
        Expression value = null;
        try
        {
            binExpr = predicate.Body as BinaryExpression;
            value = binExpr.Right;
            var func = predicate.Compile();
            return source.First(func);
        }
        catch (Exception e)
        {
            throw new Exception($" No result found for {value} {e.Message}");
        }
    }

答案 2 :(得分:0)

First()会抛出异常if no matching element is found.。因此,当您处于异常处理程序中时,您没有匹配的元素,因此不会有任何Id