我有一个列表<>包含列表<>的公会用户。两者和类型都有ID属性。
我想发现与我自己共享同一个公会的所有用户(除了有问题的公会;我们显然会分享)
是否有智能的linq和/或lambda技术来实现这一目标?
答案 0 :(得分:2)
你的问题很不清楚。不过,我还是试了一下。如果我理解正确:
你有一个看起来像这样的课程:
public class Guild
{
public List<User> Users;
public int ID;
}
两个清单:
var guilds = new List<Guild>();
var myGuilds = new List<Guild>();
你想要的是所有公会的所有用户,你也是其中的一部分。你可以用这个:
var guildUsers = new HashSet<User>((from first in guilds
join second in myGuilds
on first.ID equals second.ID
select first.Users).SelectMany(x => x)).ToList();
我们在这里做的是:
拳头,我们根据ID与两个列表相交,我们选择了各自的Users
列表:
from first in guilds
join second in myGuilds
on first.ID equals second.ID
select first.Users
然后,我们使用SelectMany
来展平列表的枚举:
.SelectMany(x => x)
然后我们将所有这些包装在HashSet中以删除重复的用户(多个公会中的用户)。
最后,我们将HashSet
转换为List<User>
(可选)。
答案 1 :(得分:1)
内部评论:
public List<User> FindSimilarUsers(List<Guild> lGuilds, List<Guild> MyGuilds)
{
// phase 1: map user to his guilds
Dictionary<int, List<int>> dUserToGuilds = new Dictionary<int, List<int>>();
lGuilds.ForEach(guild => guild.Users.ForEach(user => dUserToGuilds[user.ID] = new List<int>()));
lGuilds.ForEach(guild => guild.Users.ForEach(user => dUserToGuilds[user.ID].Add(guild.ID)));
// phase 2: map user id to corresponding user object
Dictionary<int, User> dUsers = new Dictionary<int, User>();
lGuilds.ForEach(guild => guild.Users.ForEach(user => dUsers[user.ID] = user));
// phase 3: find similar users
List<int> MyGuildsIds = MyGuilds.Select(guild => guild.ID).ToList();
return dUserToGuilds.Keys.ToList().Where(user_id => dUserToGuilds[user_id].Intersect(MyGuildsIds).Count() > 1).Select(user_id => dUsers[user_id]).ToList();
}
测试员:
static void Main(string[] args)
{
List<Guild> lGuilds = new List<Guild>();
List<Guild> MyGuilds = new List<Guild>();
User u1 = new User { ID = 1 };
User u2 = new User { ID = 2 };
User u3 = new User { ID = 3 };
User u4 = new User { ID = 4 };
Guild g1 = new Guild { ID = 1, Users = new List<User>() { u1, u2, u4 } };
Guild g2 = new Guild { ID = 2, Users = new List<User>() { u1, u3, u4 } };
Guild g3 = new Guild { ID = 3, Users = new List<User>() { u2, u4 } };
lGuilds.Add(g1);
lGuilds.Add(g2);
lGuilds.Add(g3);
MyGuilds.Add(g1);
MyGuilds.Add(g2);
FindSimilarUsers(lGuilds, MyGuilds).ForEach(user => Console.WriteLine(user.ID));
// output:
// 1
// 4
}