userkey keyboardkey keypressed
----------------------------------------
u1 kb1 A
u1 kb1 B
u1 kb2 C
u2 kb1 A
u2 kb1 B
u3 kb1 A
u3 kb1 B
u3 kb1 D
u4 kb1 E
如何将linq写入sql查询以仅获取公共按键。
例如,找到用户帐户所在的公共密钥(u1,u2,u3)和keyboardkey = kb1。这将输出为包含A,B的alist。
找到用户帐户所在的公共密钥(u1,u2,u3,u4)和keyboardkey = kb1,然后它不会返回任何内容。
感谢。
答案 0 :(得分:3)
这样的事情应该有效:
var commonKeysPressed = db.keys
.Where(k => userKeyList.Contains(k.userkey)
&& k.keyboardkey == someKeyboardkey)
.GroupBy(k => k.keypressed)
.Where( g => g.Select( x=> x.userkey).Distinct().Count() == userCount)
.Select(g => g.Key)
.ToList();
这需要:
keys
成为有问题的SQL表userKeyList
是一个用户帐户数组,即字符串数组 - 在您的示例(u1, u2, u3)
someKeyboardkey
是一些键盘键值
kb1
。userCount
userKeyList
数组中的用户数(userKeyList.Length
)答案 1 :(得分:1)
这对我有用:
var users = new [] { "u1", "u2", "u3", };
var common = users
.GroupJoin(
values.Where(v => v.keyboardkey == "kb1"),
u => u,
v => v.userkey,
(u, vs) => vs.Select(v => v.keypressed))
.Aggregate(
(zs, z) => zs.Intersect(z));
我在MySQL
数据库的LINQPad中对此进行了测试,结果正常。
答案 2 :(得分:0)
没有一行LINQ,但这是我能想到的最好的:
private List<String> GetCommonKeys(List<a> input, string[] users, string[] keyboardkeys)
{
var result = input.Where(c => users.Contains(c.userkey) && keyboardkeys.Contains(c.keyboardkey)).GroupBy (c => c.userkey);
var returnList = result.First().Select(c => c.keypressed);
foreach (var ls in result)
{
returnList = returnList.Intersect(ls.Select(t => t.keypressed));
}
return returnList.ToList();
}
struct a {
public String userkey;
public String keyboardkey;
public String keypressed;
}
编辑:作为扩展名:
public static class myExtensions
{
public static IEnumerable<TSelectType> SelectCommon<TSourceType, TSelectType>(this IEnumerable<IGrouping<TSelectType, TSourceType>> source, Func<TSourceType, TSelectType> action)
{
var firstResult = source.FirstOrDefault();
if(firstResult == null)
return new List<TSelectType>();
var returnCollection = firstResult.Select(action);
foreach(var ls in source)
returnCollection = returnCollection.Intersect(ls.Select(action));
return returnCollection;
}
}
像这样使用:
var res = lst.Where(c => new[] {"u1", "u2", "u3"}.Contains(c.userkey) && c.keyboardkey == "kb1").GroupBy (c => c.userkey).SelectCommon(c => c.keypressed);