我正在对我编写的用于搜索可查询项目的函数进行单元测试。我只是断言我得到了 1 件物品,如果该方法有效,我应该得到它。但我得到了 0 件物品。在我的方法中,我使用延迟执行并ToList
在返回之前使用。但是,如果我改为将方法更改为直接使用列表并重复调用ToList
,我会得到正确的结果。
我是否正确地说假设延迟执行产生与立即执行相同的结果是不安全的?
这是一个小应用程序,用于演示它返回 0 个项目
class Program
{
static void Main(string[] args)
{
Dictionary<string, string> values = new Dictionary<string, string>()
{
{
"Prop1",
"*Value*"
},
{
"Prop2",
"2*"
}
};
List<InputItem> items =new List<InputItem>()
{
new InputItem()
};
Console.WriteLine(Helper.SearchInputItems(items.AsQueryable(), values).Count);
Console.ReadLine();
}
}
public class InputItem
{
public Dictionary<string, string> MappedValues = new Dictionary<string, string>()
{
{
"Prop1",
"This is a value that should be found"
},
{
"Prop2",
"2 everything that begins with 2 should be found"
}
};
}
public static class Helper
{
delegate bool Searcher(string input, string searchString);
/// <summary>
/// Searches the added input items.
/// </summary>
/// <param name="values">A dictionary of field names and the search pattern for that field.</param>
/// <returns>List of found InputItems.</returns>
public static List<InputItem> SearchInputItems(IQueryable<InputItem> inputItems, Dictionary<string, string> values)
{
foreach (var value in values)
{
string searchString = value.Value;
Searcher searcher;
if (searchString.StartsWith("*") && searchString.EndsWith("*"))
{
searcher = new Searcher(StringHelpers.Contains);
searchString = searchString.Substring(1);
searchString = searchString.Remove(searchString.Length - 1);
}
else if (searchString.EndsWith("*"))
{
searcher = new Searcher(StringHelpers.StartsWith);
searchString = searchString.Remove(searchString.Length - 1);
}
else
{
searcher = new Searcher(StringHelpers.Exact);
}
inputItems = inputItems.Where(c =>
c.MappedValues.Any(x => x.Key == value.Key) &&
searcher(c.MappedValues.First(x => x.Key == value.Key).Value, searchString)
);
}
return inputItems.ToList();
}
}
public static class StringHelpers
{
public static bool Contains(string input, string searchString)
{
return input.ToUpperInvariant().Contains(searchString.ToUpperInvariant());
}
public static bool StartsWith(string input, string searchString)
{
return input.ToUpperInvariant().StartsWith(searchString.ToUpperInvariant());
}
public static bool Exact(string input, string searchString)
{
return input.ToUpperInvariant() == searchString.ToUpperInvariant();
}
}
如果我设置了一个断点,我实际上可以看到它检查是否2 everything that begins with 2 should be found
包含Value
,它不检查并返回 false。所以似乎 where 子句中的 FirstOrDefault 选择了错误的项目