c# - Linq to Entities - 将 string[] 中带有 TagID 的所有对象插入 ICollection<Tag>

标签 c# linq entity-framework asp.net-mvc-4 linq-to-entities

标签对象

  public virtual int TagID { get; set; }
  public virtual string Name { get; set; }
  public virtual string NamePlural { get; set; }

我有一个ICollection<Tag> - 和一个string[]TagID我怎样才能插入Tag对象进入ICollection<Tag>对应TagID位于 string[]数组?

我想在一个 Linq 语句(而不是循环)中执行此操作。

最佳答案

您需要在字符串数组中找到具有匹配 id 的 TagObject,因此您可以使用 Where()Contains():

ICollection<TagObject> collection;
string[] ids = new[] { "1", "2", "3" };
collection = source.Where(t => ids.Contains(t.TagID.ToString())).ToList();

TagObject 源中的每个项目都将使用 ids.Contains(t.TagID.ToString()) 表达式进行评估。如果 TagObject id 与 ids 数组匹配,则此表达式将返回 true,导致 TagObject 具有已评估为包含在 Where() 的结果中。

编辑

由于它是 Linq to Entities,因此解决该错误的简单方法是:

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.

将预先将您的 ids 数组转换为整数:

ICollection<TagObject> collection;
string[] ids = new[] { "1", "2", "3" };
int[] convertedIds = ids.Select(id => Convert.ToInt32(id)).ToArray();
collection = source.Where(t => convertedIds.Contains(t.TagID)).ToList();

关于c# - Linq to Entities - 将 string[] 中带有 TagID 的所有对象插入 ICollection<Tag>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16915412/

相关文章:

具有生成器模式的 C# 代码契约(Contract) - "Possibly calling a method on a null reference"

c# - 从 C# 控制台应用程序运行 npm init

asp.net - linq 求和与分组

entity-framework - EF5 迁移更新-数据库-脚本错误

WCF REST 服务不会返回实体的 child

c# - 使用 C# 调用带参数的 SQL Server 存储过程

c# - 隐式运算符和编译器错误

c# - 通过文本在 Linq 中选择列名

c# - 如何使用 LINQ 执行不区分大小写的 GUID 比较?

c# - 从 var 获取值