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

CSh*_*per 4 c#

我有一个匿名类型的列表,我已经tagId, isTagSelected & tagName在其中.我想要的是根据某些条件添加第4个属性

码:

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

结果:

{tagId = 1, isTagSelected = true, tagName = "a"}
{tagId = 2, isTagSelected = false, tagName = "b"}
{tagId = 3, isTagSelected = true, tagName = "c"}
Run Code Online (Sandbox Code Playgroud)

我想,如果tagNamea再加入Size = "S"其他string.emptynull.我怎样才能做到这一点?我尝试了以下方法,即在所有这些方法中添加大小,然后从不需要的地方删除,但它无法正常工作.

码:

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

结果:

{tagId = 1, isTagSelected = true, tagName = "a", Size = "S"}
{tagId = 2, isTagSelected = false, tagName = "b", Size = "S"}
{tagId = 3, isTagSelected = true, tagName = "c", Size = "S"}
Run Code Online (Sandbox Code Playgroud)

我试过foreach循环,但我可以更改只读属性.无论如何我可以Size从"b"和"c"中删除吗?

预期结果:

{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}
Run Code Online (Sandbox Code Playgroud)

小智 6

我不是在一个VS实例,但似乎这将工作.

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