2017-03-05 133 views
1

我有兩個用戶列表。基於另一個列表更新列表

在第一個用戶有以下字段 - FNAME,LNAME,UserDetailsId,FocusStart,FocusEnd,isActive

在第二列表中的用戶有 - FNAME,LNAME,UserDetailsId,TOTALTIME,FocusStart,FocusEnd。

我打算做的是:當第一個列表中的值isActive等於'true'並且userDetailsId從第二個列表中發出UserDetailsId時,我希望第二個列表中的FocusStart和FocusEnd等於值第一個列表中的匹配元素。

有關如何實現此目的的任何提示?

這裏是我得到的第一個列表:

var list = listWRUD. 
      Join(db.UsersDetails, 
      o => o.UserDetailsId, od => od.identtyUserId, 
      (o, od) => new 
      { 
       fname = od.FirstName, 
       lname = od.LastName, 
       UserDetailsId = o.UserDetailsId, 
       FocusStart = o.FocusStart, 
       FocusEnd = o.FocusEnd, 
       isActive = o.isActive 
      }).ToList(); 

     var a = from x in list 
     group x by new { x.fname, x.lname, x.UserDetailsId } into g 
     select new RolesUsersViewModel(g.Key.UserDetailsId, g.Key.fname, g.Key.lname, TimeSpan.FromMilliseconds(g.Sum(x => (x.FocusEnd - x.FocusStart).TotalMilliseconds))); 

這裏是第二個:

List<RolesUsersViewModel> list_users = a.ToList<RolesUsersViewModel>(); 

什麼我目前得到的是:

var allActive = list.Where(item => item.isActive == true); 

     foreach (var p in list_users.Join(allActive, item => item.userId, item => item.UserDetailsId, (x, y) => new { L2 = x, L1 = y })) 
     { 
      p.L2.FocusStart = p.L1.FocusStart; 
      p.L2.FocusEnd = p.L1.FocusEnd; 
     } 

可悲的是,這段代碼似乎給了我一些隨機結果。即使在第一個列表中沒有包含isActive == true的記錄,也會將日期設置爲第二個列表中的記錄。

視圖模型:

公共類RolesUsersViewModel { 公共RolesUsersViewModel(字符串userDetailsId,串名字,串名字,時間跨度totalex) {

userId = userDetailsId; 
    fname = FirstName; 
    lname = LastName; 
    total = totalex; 
} 

public RolesUsersViewModel(DateTime focusStart, DateTime focusEnd)// 
{ 

    FocusStart = focusStart; 
    FocusEnd = focusEnd; 
} 

public string userId { get; set; } 
public string fname { get; set; } 
public string lname { get; set; } 
public TimeSpan total { get; set; } 
public DateTime FocusStart { get; set; }// 
public DateTime FocusEnd { get; set; }// 

}

+0

什麼做你的意思是'我希望FocusStart和FocusEnd在第二個列表中等於matc的值hed元素在第一個列表中。你想分配FocusStart和FocustEnd嗎? – CodingYoshi

+0

@CodingYoshi是的,這是正確的。 –

+0

'item.userId'來自哪裏? –

回答

1
foreach (var p in list_users) 
{ 
    // Get all the items that have matching UserDetailsId 
    var targets = allActive.Where(x => x.UserDetailsId == p.UserDetailsId); 

    // Now assign the properties 
    // my assumption is that the above query should return 
    // a single record. If my assumption is true then use 
    // Single or SingleOrDefault and then you do not need 
    // the loop below but just a simple assignment 
    foreach(var thisTarget in targets) 
    { 
     p.FocusStart = thisTarget.FocusStart; 
     p.Focused = thisTarget.FocusEnd; 
    } 
} 
+0

關於thisTarget我得到了「索引器的屬性...不能被分配給」。 「 –

+0

@robertross是屬性只讀? – CodingYoshi

+0

我不這麼認爲,它有{get; set;},它告訴我它不是。但顯然我的知識是有限的。 –