比较2个linq列表中的2个属性,并根据比较返回一个布尔值

时间:2018-05-02 13:33:48

标签: c# linq

我试图找到答案,但似乎没有任何东西适合它。

要求:从已知的FooObject列表中,返回其数据满足所有搜索条件的Foo Id列表。

这是我的代码:

class testClass
{
    public class SearchItem
    {
        string Term { get; set; }
        decimal Confidence { get; set; }
    }

    public class FooObject
    {
        public Guid Id { get; set; }
        public List<Data> Data { get; set; }

    }

    public class Data
    {
        public string Text { get; set; }
        public decimal Confidence { get; set; }
    }

    [Test]
    public void Test()
    {
        var searchItems = new List<SearchTerm>
            {
                new SearchTerm{ Confidence = (decimal)1, Term = "TestWord" },
                new SearchTerm{ Confidence = (decimal)1, Term = "TestWord2" },

            };
        var FooObjects = new List<FooObject>
            {
                new FooObject{Id = new Guid(), Data = new List<Data>
                    {                                                                                     
                        new Data{Text = "TestWord", Confidence = 1}, 
                        new Data{Text = "TestWord2", Confidence = 1},                                                                                     
                        new Data{Text = "SomeOtherWord", Confidence = 1},                                                                                  
                    }
            }
        }; 
//result is a list of the Foo IDs
        var result = FooObjects.Where(foo => !searchItems.Select(item => item.Term).Except(foo.Data.Select(dt => dt.Text).Distinct()).Any())
                     .Select(foo => foo.Id).ToList();

        Assert.That(result.Count, Is.EqualTo(1));
        searchItems.Add(new SearchTerm{Term = "NotFoundString"});
        result = FooObjects.Where(foo => !searchItems.Select(item => item.Term).Except(foo.Data.Select(dt => dt.Text).Distinct()).Any())
      .Select(foo => foo.Id).ToList();

        Assert.That(result.Count, Is.EqualTo(0));
    }
}

我现在需要对此进行修改,以便与每个单词的置信度进行比较

问题: 如何修改LINQ以比较置信度和术语与我的数据

2 个答案:

答案 0 :(得分:1)

而不是匹配任何标准,如@dymanoid在他的回答中说,你应该寻求满足所有的搜索项/术语(你在你的示例代码中混合这些,是一致的)。

var result = FooObjects
    .Where(f => searchItems.All(
        s => f.Data.Exists(d => d.Text == s.Term && d.Confidence == s.Confidence)))
    .Select(f => f.Id);

答案 1 :(得分:0)

也许你正在寻找这样的东西:

var result = FooObjects
    .Where(foo => foo.Data.Any(d => searchTerms.Any(
        si => d.Term == si.Text && d.Confidence == si.Confidence)))
    .Select(foo => foo.Id);

请记住,此搜索无效 - 如果您的数据集较大,则性能会很差。