update multiple elements at once LINQ

前端 未结 6 2029
萌比男神i
萌比男神i 2020-12-17 08:42

Is it possible to set property on each element from List using LINQ.

for example:

var users = from u in context.Users where u.Name == \"George\" sele         


        
相关标签:
6条回答
  • 2020-12-17 08:58

    How about:

     context.Users.Where(u => u.Name == "George").Select(u => u.MyProp = false);
    
    0 讨论(0)
  • 2020-12-17 09:02

    You can create your own ForEach extension method:

    public static IEnumerable<T> ForEach<T>(this IEnumerable<T> source, Action<T> action)
    {
        foreach (var element in source)
        {
            action(element);
        }
    
        return source;
    }
    

    Then your code can be simplified to:

    context.Users.Where(x => x.Name == "George").ForEach(u => u.MyProp = false);
    

    EDIT: You could also yield return each item after the call to action() (no pun intended) to leave the deferred execution untouched.

    0 讨论(0)
  • 2020-12-17 09:09

    Looks dirty but if asked (just via select), I'll do it this way

    var users = from u in context.Users where u.Name == "George" 
    select new User() 
    {
       prop1 = u.prop1,
       prop2 = u.prop2,
       prop3 = true // update like here
    };
    

    if you wish to use some other C# function, you can also use linq functions and work on IEnumerable type of lists.

    var users = context.Users.Where(u => u.Name == "George").ToList()
        .Select(p => new User() 
        {
           prop1 = p.prop1,
           prop2 = p.prop2,
           prop3 = ComputeHash(p) // update like here
        });
    

    Code above becomes IEnumerable because of the .ToList() prior to the .Select()

    0 讨论(0)
  • 2020-12-17 09:15

    What is cleaner is quite subjective. Personally, I find this approach hard to beat for clarity and simplicity:

    foreach (User us in users.Where(u => u.Name == "George"))
    {
       us.MyProp = false;
    }
    
    0 讨论(0)
  • 2020-12-17 09:22

    Or you can convert it to ToList() and use ForEach method.

    users.ToList().ForEach(u => u.MyProp = false);
    

    to update more than one properties

    users.ToList().ForEach(u =>
                          {
                             u.property1 = value1;
                             u.property2 = value2;
                          });
    

    Or like this

    (from u in context.Users where u.Name == "George" select u).ToList()
    .ForEach(u => u.MyProp = false);
    
    0 讨论(0)
  • 2020-12-17 09:24

    If you're interested in in-memory update, that is the database is not going to be updated then you could use

    var users = (from u in context.Users where u.Name == "George" select u).ToList();
    users.ForEach(u => u.MyProp = "Something");
    
    0 讨论(0)
提交回复
热议问题