繁体   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