【问题标题】:Search matched list in dictionary在字典中搜索匹配列表
【发布时间】:2012-07-31 14:26:02
【问题描述】:
public class Filter
{
    public List<int> A { get; set; }
    public DateTime Start { get; set; }
    public DateTime End { get; set; }
}
var f1 = new Filter(){A = new List<int>() {1}}
var f2 = new Filter(){A = new List<int>() {1 , 4, 2}, Start = DateTime.Now, End = DateTime.AddHour(2)}

var dict = new Dictionary<Filter, string>()
dict.Add(new Filter(){A = new List<int>() {1}}, "asdf");
dict.Add(new Filter(){A = new List<int>() {4}}, "qwerty");
dict.Add(new Filter(){A = new List<int>() {3}}, "qwertyasd");

我需要得到:

f1 项目优先

f2 第一个和第二个项目。

如何构造linq查询?

Aint 时,很简单

dict.Where(k =>
k.Key.A.Equals(filter.A)
&& k.Key.Start.CompareTo(filter.Start) > 0 
&& k.Key.End.CompareTo(filter.End) < 0
)

但是当它是 List&lt;int&gt; 时,它对我来说更复杂。

【问题讨论】:

    标签: c# linq dictionary compare predicates


    【解决方案1】:

    只需使用Contains 并反转控件

    dict.Where(k =>
        filter.A.Contains(k.Key.A[0]) //CONTAINS !
        && k.Key.Start.CompareTo(filter.Start) > 0 
        && k.Key.Start.CompareTo(filter.End) < 0
    )
    

    【讨论】:

    • 'System.Collections.Generic.List.Contains(int)' 的最佳重载方法匹配有一些无效参数。 = 我不能使用 List 作为参数
    • @Saint:我编辑了我的帖子。我假设字典中的列表总是只包含单个元素。
    • @Tigran 更好。我稍后会检查它,但可能应该有效
    • @RaphaëlAlthaus 也是 4.0。嗯,奇怪
    【解决方案2】:

    你可以使用Intersect方法

    dict.Where(k =>
                k.Key.A.Intersect(filter.A).Any()
                && k.Key.Start.CompareTo(filter.Start) > 0
                && k.Key.End.CompareTo(filter.End) < 0
            );
    

    编辑:添加了Intersect,因为涉及到两个列表。

    【讨论】:

    • 'System.Collections.Generic.List.Contains(int)' 的最佳重载方法匹配有一些无效参数。 = 我不能使用 List 作为参数
    【解决方案3】:

    如果Filter.A的至少一个元素必须匹配dict.Key.A的一个元素,你也可以这样做。

    因为我没有看到拥有一个列表的兴趣...只需要一个 int !

    var result = dict.Where(k =>
                               filter.A.Intersect(k.Key.A).Any());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-25
      • 2015-07-03
      • 1970-01-01
      • 2022-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-27
      相关资源
      最近更新 更多