标签对象
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/