【问题标题】:Group by with linq to update collection使用 linq 分组以更新集合
【发布时间】:2015-06-23 10:02:15
【问题描述】:

我有一个名为 allEventsDetails 的 IEnumerable 集合和集合属性 是数字、名称和状态。

如果两个或多个数字值相等,我需要更新同一个集合。

var categories =  from p in allEventsDetails
                  group p by p.Digit into g
                  where g.Count() > 1
                  select g.Select(s => s.status = "true");

我如何使用 linq 来做到这一点?

【问题讨论】:

  • linkq 通常用于检索数据...使用 LINQ 无法进行更新...通过 linq 查询更新数据的唯一可能方法是通过扩展方法
  • LINQ 是一种查询语言,它不做任何修改。修改由您正在使用的 ORM 执行,并且是特定于它的。你用的是什么ORM?另一方面,如果您使用的是内存中的集合,只需修改属性

标签: c# asp.net linq asp.net-mvc-4


【解决方案1】:

你可以这样做:

(from x in allEventsDetails
  group x by x.Digit into y
  where y.Count()>1
  select y).SelectMany(z=>z).ToList().ForEach(x=>x.Status="true");

你还可以做的是:

var temp= (from x in allEventsDetails
  group x by x.Digit into y
  where y.Count()>1
  select y).SelectMany(z=>z);

  foreach (var x in temp)
  {
     x.Status= "test";
  }

这样您就不必创建“临时”列表。

【讨论】:

  • ForEachList 上的一个方法,不是 LINQ 的一部分。不过,无需创建临时列表,只需遍历结果并设置状态即可。
  • 是的,你可以。只是在一个“批次”中更新。好吧,LINQ 只是 C# 之上的语法糖,编译器随后将其转换为 Enumerable/Querable 的一系列扩展方法。
  • @Aruns 查看我对 Panagiotis 含义的更新答案
猜你喜欢
  • 1970-01-01
  • 2011-06-29
  • 2010-12-04
  • 2010-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多