我有以下3个表作为简单的“项目标记”模式的一部分:
== ==项目
== ==标签
== TagMap ==
我想写一个LINQ查询来带回与标签列表匹配的项目(例如TagId = 2,3,4,7)。在我的应用程序上下文中,项目的示例将是“计算机监视器”,“衬衫”,“吉他”等,标签的示例将是“电子”,“服装”等。我通常会使用SQL来实现这一点。在声明中。
就像是
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子句)。
给定的项目数组:
var list = new int[] {2,3,4}
使用:
where list.Contains(tm.TagId)
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();
你可以简单地使用,
var TagIds = {12, 32, 42}
var prod =entities.TagMaps.Where(tagmaps=> TagIds .Contains(tagmaps.TagId));
string[] names = {"John", "Cassandra", "Sarah"};
var results = (from n in db.Names
where names.Contains(n.Name)
select n).ToList();
您可以创建一个扩展方法“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;
或者只使用内联array.Contains()表示法:
var q = from map in Context.TagMaps
where new[]{2, 3, 4, 7}.Contains(map.TagId)
select map.Items;