簡體   English   中英

如何在c#中更新匿名列表中的值

[英]How to update value in anonymous list in c#

我有一個匿名類型的列表,我有tagId, isTagSelected & tagName 我想要的是根據某些條件添加第4個屬性

碼:

var tagDetails = tagIdList.Select((x, i) => new { tagId = x, isTagSelected = tagSelectionList[i], tagName = tagList[i] }).ToList();

結果:

{tagId = 1, isTagSelected = true, tagName = "a"}
{tagId = 2, isTagSelected = false, tagName = "b"}
{tagId = 3, isTagSelected = true, tagName = "c"}

我想要的是,如果tagNamea然后添加Size = "S" else string.emptynull 我怎樣才能做到這一點? 我嘗試了以下方法,即在所有這些方法中添加大小,然后從不需要的地方刪除,但它無法正常工作。

碼:

var tagDetails = tagIdList.Select((x, i) => new { tagId = x, isTagSelected = tagSelectionList[i], tagName = tagList[i], itemSize = itemSize }).ToList();

結果:

{tagId = 1, isTagSelected = true, tagName = "a", Size = "S"}
{tagId = 2, isTagSelected = false, tagName = "b", Size = "S"}
{tagId = 3, isTagSelected = true, tagName = "c", Size = "S"}

我嘗試了foreach循環,但我可以更改只讀屬性。 無論如何我可以從“b”和“c”中刪除Size嗎?

預期結果:

{tagId = 1, isTagSelected = true, tagName = "a", Size = "S"}
{tagId = 2, isTagSelected = false, tagName = "b", Size = "" or null}
{tagId = 3, isTagSelected = true, tagName = "c", Size = "" or null}

我不是在一個VS實例,但似乎這將工作。

var tagDetails = tagIdList.Select((x, i) => new 
        { tagId = x,
          isTagSelected = tagSelectionList[i], 
          tagName = tagList[i], 
          Size = tagList[i] == "a" ? "S" : null 
    }).ToList();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM