如何将具有多个`from`的LINQ表达式从查询语法转换为方法语法?

时间:2013-02-13 09:11:25

标签: c# lambda

我使用实体框架。我如何在Lambda C#中编写以下Linq-Code?

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。

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

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

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

请注意,我在ToList()上省略了context.Users的电话,因为这似乎没必要。

答案 2 :(得分: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();