3

我正在对我编写的用于搜索可查询项目的函数进行单元测试。我只是断言我得到了 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 选择了错误的项目

4

1 回答 1

3

好的,我明白了。这是捕获循环变量的老问题。

这里:

        foreach (var value in values)
        {
            ...
            inputItems = inputItems.Where(c =>
                c.MappedValues.Any(x => x.Key == value.Key) &&
                searcher(c.MappedValues.First(x => x.Key == value.Key).Value, 
                                              searchString)
                );

        }

您在valuelambda 表达式中使用,这意味着它将value在执行时使用“当前值”......并且该值随着循环迭代而变化。

只需使用:

foreach (var valueIterationVariable in values)
{
    var value = valueIterationVariable;
    // code as before
}

我相信会没事的。(顺便说一句,我会质疑你使用“价值”这个名字,但那是另一回事。)

我还没有深入研究为什么它可以工作IEnumerable<T>但不能工作IQueryable<T>,但我怀疑额外的延期是罪魁祸首。

于 2011-08-11T09:37:23.687 回答