根据其他列表更新列表

时间:2017-03-05 00:07:44

标签: c# linq list

我有两个用户列表。

在第一个用户有以下字段 - 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的记录,也会将日期设置为第二个列表中的记录。

ViewModel:

公共类RolesUsersViewModel {     public RolesUsersViewModel(string userDetailsId,string FirstName,string LastName,TimeSpan 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; }//

}

1 个答案:

答案 0 :(得分: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;
    } 
}