简体   繁体   English

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

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

I have a list which is anonymous type and I've tagId, isTagSelected & tagName in it. 我有一个匿名类型的列表,我有tagId, isTagSelected & tagName What I want is want to add 4th property based on some condition 我想要的是根据某些条件添加第4个属性

Code: 码:

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

Result: 结果:

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

What I want is, if tagName is a then add Size = "S" else string.empty or null . 我想要的是,如果tagNamea然后添加Size = "S" else string.emptynull How can I achieve this? 我怎样才能做到这一点? I tried following approach which is, add Size in all of them and then remove from unwanted place but it is not working. 我尝试了以下方法,即在所有这些方法中添加大小,然后从不需要的地方删除,但它无法正常工作。

Code: 码:

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

Result: 结果:

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

I tried foreach loop but I can change read only property. 我尝试了foreach循环,但我可以更改只读属性。 Is there anyway that I can remove Size from "b" & "c"? 无论如何我可以从“b”和“c”中删除Size吗?

Expected Result: 预期结果:

{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}

Im not at a VS instance but it seems like this would work. 我不是在一个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