簡體   English   中英

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

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

我有這個課:

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

我使用Enumerable.Repeat靜態方法創建了一組10個元素:

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

這些將創建具有相同屬性的10個Documents 我需要他們中的一些,例如,列表的第5個元素listChecked屬性為false

我如何使用linq來實現它?

請注意,您的原始示例存在一個錯誤,因為它正在創建一個只有10個實際Document對象的10個元素的List<Document> 這是一種更好的方法

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

編輯

將代碼更改為更簡單。 我最初的反應是編輯一個已經存在的列表,可以執行以下操作

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

請注意,您可能必須為此操作定義一個簡單的ForEach方法。 如果您沒有定義,這里是一個例子

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

完成您要求的替代方法(也用“ 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