当Where子句不满足时,LINQ扩展方法是否可以使用new().Value创建新的KeyValuePair

end*_*hin 2 .net c# linq extension-methods linq-extensions

我有一个集合

List<KeyValuePair<string, Details>> x
Run Code Online (Sandbox Code Playgroud)

哪里

public class Details
{ 
    private int x;
    private int y;

    public Details()
    {
        x = 0;
        y = 0;
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

我在我的集​​合上使用LINQ来返回Details实例

x.Where(x => x.Key == aString).SingleOrNew().Value
Run Code Online (Sandbox Code Playgroud)

在哪里.SingleOrNew定义为

public static T SingleOrNew<T>(this IEnumerable<T> query) where T : new()
{            
    try
    {
       return query.Single();
    }
    catch (InvalidOperationException)
    {
       return new T();
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,如果KeyValuePair<string, Details>在列表x中找不到满足Where条款a的a,new KeyValuePair<string, Details>则返回.

但问题是new KeyValuePair<string, Details>包含null Details值.

当从.Where子句中找不到匹配时,我想知道是否可以使用任何LINQ(扩展)方法,它会返回new KeyValuePair<string, Details>类似SingleOrNew但是使用默认的无参数构造函数初始化.Value/的Details部分?所以它不是空的!KeyValuePairDetails

sma*_*man 5

请改用此扩展方法:

    public static T SingleOrNew<T>(this IEnumerable<T> query, Func<T> createNew) 
    {
        try
        {
            return query.Single();
        }
        catch (InvalidOperationException)
        {
            return createNew();
        }
    }
Run Code Online (Sandbox Code Playgroud)

您可能还想拥有它,因此您不需要Where()子句:

    public static T SingleOrNew<T>(this IEnumerable<T> query, Func<T,bool> predicate, Func<T> createNew) 
    {
        try
        {
            return query.Single(predicate);
        }
        catch (InvalidOperationException)
        {
            return createNew();
        }
    }
Run Code Online (Sandbox Code Playgroud)

现在,您可以指定T的新实例应该是什么,而不是限制为T的默认值,并具有公共无参数构造函数的约束.