简体   繁体   English

如何在C#中使用linq修改列表的某些元素?

[英]How to modify some elements of a list using linq in C#?

I have this class: 我有这个课:

public class Document
{
    public string ID { get; set; }
    public string Type { get; set; }
    public bool Checked {get;set; }
}

I create a set of 10 elements using Enumerable.Repeat static method: 我使用Enumerable.Repeat静态方法创建了一组10个元素:

var list = Enumerable.Repeat<Document>(
            new Document
            {
                ID="1",
                Type ="someType"
                Checked = true
            }, 10).ToList<Document>();

These creates 10 Documents all with the same properties. 这些将创建具有相同属性的10个Documents I need that some of them, for instance, the first 5 elements of the list list have the Checked property to false . 我需要他们中的一些,例如,列表的第5个元素listChecked属性为false

How can I achieve it, using as possible linq ? 我如何使用linq来实现它?

Note that your original sample has a bug because it's creating a 10 element List<Document> that only has 1 actual Document object. 请注意,您的原始示例存在一个错误,因为它正在创建一个只有10个实际Document对象的10个元素的List<Document> Here is a better way of doing it 这是一种更好的方法

Enumerable
  .Range(1, 10)
  .Select(i => 
    new Document() { 
      ID = "1",
      Type = "someType",
      Checked = i <= 5
    })
  .ToList();

EDIT 编辑

Changed the code to be simpler. 将代码更改为更简单。 My original response was to editing an already existing list for which the following can be done 我最初的反应是编辑一个已经存在的列表,可以执行以下操作

list.Take(5).ForEach(x => { x.Checked = false });

Note that you may have to define a simple ForEach method for this operation. 请注意,您可能必须为此操作定义一个简单的ForEach方法。 If you don't have one defined here is an example 如果您没有定义,这里是一个例子

static class Extensions { 
  internal static void ForEach<T>(this IEnumerable<T> e, Action<T> action) {
    foreach (var item in e) { 
      action(item); 
    }
  }
}

Alternate idea to accomplish what you're asking for (also populates your ID column with something other than "1") : 完成您要求的替代方法(也用“ 1”以外的内容填充ID列)

var list = Enumerable.Range(1, 10)
                     .Select(i => new Document
                     {
                         ID = i.ToString(),
                         Type = "someType",
                         Checked = (i > 5)
                     }).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM