简体   繁体   English

C#:如何从LINQ结果获取匿名类型

[英]C# : How to get anonymous type from LINQ result

I need to get NewsImage field and list of categories Ids that associated with the news in Many to Many relationship ... but it gives me error: 我需要获取NewsImage字段和与“多对多”关系中的新闻相关联的类别ID的列表...但它给我错误:

The type of one of the expressions in the join clause is incorrect.Type inference failed in the call to 'Join'. join子句中的表达式之一的类型不正确。在调用“ Join”时类型推断失败。

My code looks like this 我的代码看起来像这样

  var Result1 = (from c in db.News
                   join d in db.Categories
                on c.NewsId equals d.News.Select(l => l.NewsId)
                   where c.NewsId == 1
                   select new { c.NewsImagePath, d.CategoryId }).ToList();

The problem is inside the on statement. 问题出on语句中。

on c.NewsId equals d.News.Select( l => l.NewsId )

The Select on the right-hand side will return a IEnumerable of news, which is not what you want. 右侧的“选择”将返回一个IEnumerable新闻,这不是您想要的。

Something like this would technically work: 这样的事情在技术上会起作用:

on c.NewsId equals d.News.Select( l => l.NewsId ).FirstOrDefault()

But it does not make sense logically. 但这在逻辑上没有意义。

I suspect the whole query should be built differently. 我怀疑整个查询应该以不同的方式构建。 I think you want to join when the category list of news contains the news item. 我认为您希望在新闻类别列表包含新闻项时加入。 In that case, you can't use the join statement, it would look somewhat like this: 在这种情况下,您不能使用join语句,它看起来像这样:

from n in db.News
from c in db.Categories
where c.News.Select( ne => ne.NewsId ).Contains( n.NewsId )
select new { n.NewsImagePath, c.CategoryId }

Assuming you have a navigation property defining the nn relation I would write: 假设您有一个定义nn关系的导航属性,我将这样写:

var result = db.News
  .Where(x => x.NewsId == 1)
  .SelectMany(x => x.Categories, 
              (news, category) => new { news.NewsImagePath, category.CategoryId })
  .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM