我有以下3个表作为简单的“项目标记”模式的一部分:
==项==
==标签==
== TagMap ==
我想写一个LINQ查询来带回与标签列表匹配的项目(例如TagId = 2,3,4,7)。在我的应用程序上下文中,项目的示例将是“计算机监视器”,“衬衫”,“吉他”等,标签的示例将是“电子”,“服装”等。我通常会使用SQL来实现这一点。 IN声明。
答案 0 :(得分:49)
像
这样的东西var TagIds = new int[] {12, 32, 42};
var q = from map in Context.TagMaps
where TagIds.Contains(map.TagId)
select map.Items;
应该做你需要的。这将生成一个In(12,32,42)子句(或者更具体地说是一个参数化的IN子句,如果我没有弄错的话)。
答案 1 :(得分:15)
给出一系列项目:
var list = new int[] {2,3,4}
使用:
where list.Contains(tm.TagId)
答案 2 :(得分:1)
List<int> tagIds = new List<int>() {2, 3, 4, 7};
int tagIdCount = tagIds.Count;
//
// Items that have any of the tags
// (any item may have any of the tags, not necessarily all of them
//
var ItemsAnyTags = db.Items
.Where(item => item.TagMaps
.Any(tm => tagIds.Contains(tm.TagId))
);
//
// Items that have ALL of the tags
// (any item may have extra tags that are not mentioned).
//
var ItemIdsForAllTags = db.TagMap
.Where(tm => tagIds.Contains(tm.TagId))
.GroupBy(tm => tm.ItemId)
.Where(g => g.Count() == tagIdCount)
.Select(g => g.Key);
//
var ItemsWithAllTags = db.Items
.Where(item => ItemsIdsForAllTags.Contains(item.ItemId));
//runs just one query against the database
List<Item> result = ItemsWithAllTags.ToList();
答案 3 :(得分:1)
你可以简单地使用,
var TagIds = {12, 32, 42}
var prod =entities.TagMaps.Where(tagmaps=> TagIds .Contains(tagmaps.TagId));
答案 4 :(得分:0)
string[] names = {"John", "Cassandra", "Sarah"};
var results = (from n in db.Names
where names.Contains(n.Name)
select n).ToList();
答案 5 :(得分:0)
您可以创建扩展方法“ IN()”
public static class Extension
{
public static bool IN(this object anyObject, params object[] list)
{ return list.Contains(anyObject); }
}
要像这样使用
var q = from map in Context.TagMaps
where map.TagId.IN(2, 3, 4, 7)
select map.Items;
或仅使用内联数组。Contains()表示法:
var q = from map in Context.TagMaps
where new[]{2, 3, 4, 7}.Contains(map.TagId)
select map.Items;