只有在找到完全匹配时才选择Linq

时间:2016-02-02 04:08:48

标签: c# linq

我有一张如下所示的表格

user | roomNo
--------------
  A  | R1
  B  | R1
  A  | R2
  C  | R2
  A  | R3
  B  | R3
  E  | R3

此外,我有一个用户列表,其中数字不确定(根据传入的参数,但至少会有2个用户。)

这是我得到用户的方法: var user = userlist.Split(',');

我的问题是: 我如何使用linq获取roomNo以获得用户数量和用户值

的完全匹配

示例:

  1. 有2个用户(用户是A和B),系统应该返回roomNo R1
  2. 有3个用户(用户是A,B和E),系统应该返回roomNo R3

2 个答案:

答案 0 :(得分:1)

假设您有类似这样的数据结构:

class Reservation
{
    public string User { get; set; }
    public string RoomNo { get; set; }
}

这将查询您之后的内容:

var input = new[] { "A", "B", "E" };

// start with reservations
var room = reservations
    // create a grouping by the room number
    .GroupBy(r => r.RoomNo)
    // filter groupings that contain all `input` elements
    .Where(g => input.All(i => g.Select(rs => rs.User).Contains(i)))
    // filter groupings to those whose reservations only include elements in `input` 
    .Where(g => g.All(r => input.Contains(r.User)))
    // select the grouping key, which is the room number. 
    .Select(g => g.Key);

答案 1 :(得分:0)

下面你可以试试:

var usersWhoHaveBookedRooms = db.UserRoomInfoTbl.Where(x=> users.contains(x.user)).ToList();

var bookedRooms = (from item in usersWhoHaveBookedRooms 
                   group item by item.roomNo
                   select item).ForEach(x=> new {
                   RoomNumber = x.Key,
                   Users = x.Value //Note: cretea csv of userid from here
                   }).ToList()

代码只是给出一个想法。它不会编译。