LINQ to SQL,内存列表和匿名类型

时间:2012-02-01 07:54:33

标签: linq-to-sql anonymous-types

我正在将表连接到内存列表中,并希望从结果中创建匿名类型。我已经加入了2个数据源,但是我不确定在匿名类型的内存列表中使用属性所需的语法。

这是我的代码

        public DataKeys(IEnumerable<Element> elements)
    {
        var defsource = new DefinitionSource();
        var items = from def in defsource.Definitions
                    where elements.Select(el=> el.Value).Contains(def.Name)                        
                    select new { def.Key };
        ...

    }

(显然“elements”是元素的内存列表,“DefinitionSource”是表的包装。)这很好用,但正如你所看到的,内存中的元素列表没有属性。我试过这个

      var items = from def in defsource.Definitions
                  where elements.Select(el=> el.Value).Contains(def.Name)  
                  from el in elements
                  where el.Value.Equals(def.Name)
                  select new { el.NodeType, def.Key };

但是在运行时它发出“{”本地序列不能用于查询运算符的LINQ to SQL实现,除了Contains运算符。“}”

那么我需要做什么语法呢?

很多thx IA

西蒙

2 个答案:

答案 0 :(得分:1)

这可能会有所帮助:

var def=defsource.Definitions
                    .Where(a=>elements.Select(el=>el.Value).Contains(a.Name))
                    .ToList();
var items = from d in def
          from el in elements
            .Where(a=>a.Value==d.Name)
                  select new { el.NodeType, d.Key };

答案 1 :(得分:1)

要查询两个数据源,它们都需要在内存中,它们都应该在数据库中。您可以执行以下操作以获得所需的结果

var query = (from def in defsource.Definitions
                  where elements.Select(el=> el.Value).Contains(def.Name)  
                  ).ToList();//bring filtered result in memory
var Items = from def in query //Definitions are already filtered no need to re-apply where
            from el in elements.Where(a=>a.Value == def.Name)
            select new {el.NodeType, def.Key};