0

我正在使用实体框架。我将如何在 Lambda C# 中编写以下 Linq 代码?

var users = (from u in context.Users.ToList()
                         from e in u.Events
                         where e.EventName == eventName //Name of the Event, the user is related to
                         select u.FirstName + u.LastName).ToList();

在这种情况下无法通过 Lambda。

4

3 回答 3

3
context.Users.SelectMany(u => u.Events.Where(e => e.EventName == eventName).
                                       Select(e => u.FirstName + u.LastName)).
              ToList();
于 2013-02-13T09:22:37.287 回答
2

“方法链”中的等价物(这就是它的名称)如下所示:

context.Users.SelectMany(u => u.Events
                               .Where(e => e.EventName == eventName)
                               .Select(e => u.FirstName + u.LastName))
             .ToList();

请注意,我省略了对ToList()on的调用,context.Users因为它似乎没有必要。

于 2013-02-13T09:14:13.743 回答
0
var users = context.Users
            .Where(u => u.Events.Any(q => q.EventName == eventName))
            .Select(m => m.FirstName + m.LastName).ToList();

更新,添加测试相关类;

public class User
{
    public List<Event> Events { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Event
{
    public string EventName { get; set; }
}

和代码;

string eventName = "a";

List<User> t = new List<User>();

Event event1 = new Event() { EventName = "a" };
Event event2 = new Event() { EventName = "b" };
Event event3 = new Event() { EventName = "c" };

User user1 = new User() { FirstName = "x", LastName = "y" };
User user2 = new User() { FirstName = "x1", LastName = "y1" };
User user3 = new User() { FirstName = "x2", LastName = "y2" };

user1.Events = new List<Event>();
user2.Events = new List<Event>();
user3.Events = new List<Event>();

user1.Events.Add(event1);
user1.Events.Add(event2);

user2.Events.Add(event2);
user2.Events.Add(event3);

user3.Events.Add(event1);
user3.Events.Add(event3);

t.Add(user1);
t.Add(user2);
t.Add(user3);

var bb = t.Where(u => u.Events.Any(q => q.EventName == eventName)).Select(m => m.FirstName + m.LastName).ToList();
于 2013-02-13T09:15:18.467 回答