代码之家  ›  专栏  ›  技术社区  ›  Xander

如何将结果与数组匹配

  •  0
  • Xander  · 技术社区  · 15 年前

    我使用带有contains关键字的linq to entities查询来返回表中与值匹配的所有结果。

    现在的问题是。。。我想将结果与对象索引匹配。。。

    我几乎希望查询结果返回以下内容:

    index = 1;
    value = "searchkey"
    queryvalue = "query value"
    
    2 回复  |  直到 15 年前
        1
  •  1
  •   Enigmativity    15 年前

    根据你的问题,我想我可以假设你定义了以下变量:

    • Lookup[] (您查找数组)
    • IEnumerable<Record> (查询返回的结果)

    ... 类型大致如下:

    public class Lookup
    {
        public int Index { get; set; }
        public int Value { get; set; }
    }
    
    public class Record
    {
        public int Value { get; set; }
        /* plus other fields */
    }
    

    首先使用匿名类型:

    var matches
        = from r in records
          join l in lookups on r.Value equals l.Value
          group r by l.Index into grs
          select new
          {
              Index = grs.Key,
              Records = grs.ToArray(),
          };
    

    另外两个只使用标准LINQ GroupBy ToLookup :

    IEnumerable<IGrouping<int, Record>> matches2
        = from r in records
          join l in lookups on r.Value equals l.Value
          group r by l.Index;
    
    ILookup<int, Record[]> matches3
        = matches2.ToLookup(m => m.Key, m => m.ToArray());
    

        2
  •  1
  •   Roly    15 年前

    对于您需要什么,只需要一个暗中的快照,但是LINQ扩展方法可以将索引作为lambda函数的第二个参数来处理。即:

    someCollection.Select((x,i)=>新建{SomeProperty=x.Property,Index=i});