How to Set Value for Property of an Anonymous Object

How to set value for property of an anonymous object?

Anonymous type properties are read only and they cannot be set.

Anonymous types provide a convenient way to encapsulate a set of
read-only properties
into a single object without having to explicitly
define a type first. The type name is generated by the compiler and is
not available at the source code level. The type of each property is
inferred by the compiler.

Anonymous Types (C# Programming Guide)

Using value of a property as property name in anonymous object

You could project each grouping to a dictionary. Then you serialize it and get desired output:

var output = locales.Where(x => x.ParentKey != null)
.GroupBy(x => x.ParentKey)
.Select(x => new {
lang = x.Key,
data = x.ToDictionary(k => k.Key, v => v.Value)
});

var json = Newtonsoft.Json.JsonConvert.SerializeObject(output);

For example data:

var locales = new List<Locale> {
new Locale { LanguageId = 1, Key = "a", Value = "1", ParentKey = "1" },
new Locale { LanguageId = 2, Key = "b", Value = "2", ParentKey = "2" },
new Locale { LanguageId = 3, Key = "c", Value = "3", ParentKey = "2" },
};

yields:

[{"lang":"1","data":{"a":"1"}},
{"lang":"2","data":{"b":"2","c":"3"}}]

How to define anonymous object property dynamically?

Anonymous types are immutable, you can only create and set properties when creating the instance. This means you need to create the exact object you need. So you could do something like this instead:

if (fields.Contains("picture_url"))
{
return Ok(new
{
id = userProfile.UserId,
email = userProfile.Email,
name = userProfile.Name,
picture_url = "path"
});
}

return Ok(new
{
id = userProfile.UserId,
email = userProfile.Email,
name = userProfile.Name
});

Another option is to used a Dictionary<string, object>. For example:

var userInfo = new Dictionary<string, object>
{
{"id", userProfile.UserId},
{"email", userProfile.Email},
{"name", userProfile.Name}
};

if (fields.Contains("picture_url"))
{
// error in this line
userInfo.Add("picture_url", "path");
}

return Ok(userInfo);

This object will serialise to the same JSON structure:

{"id":1,"email":"email@somewhere.com","name":"Bob","picture_url":"path"}

How can I get a value of a property from an anonymous type?

Have you ever tried to use reflection? Here's a sample code snippet:

// use reflection to retrieve the values of the following anonymous type
var obj = new { ClientId = 7, ClientName = "ACME Inc.", Jobs = 5 };
System.Type type = obj.GetType();
int clientid = (int)type.GetProperty("ClientId").GetValue(obj, null);
string clientname = (string)type.GetProperty("ClientName").GetValue(obj, null);

// use the retrieved values for whatever you want...

Typing the properties of an anonymous object in TypeScript

function someFunction({ propertyA, propertyB }: {propertyA: boolean; propertyB: number }){
//...

or, better yet: make an explicit type:

interface SomeFunctionOpts{
propertyA: boolean;
propertyB: number;
}

function someFunction({ propertyA, propertyB }: SomeFunctionOpts) {
//...

How to update value in anonymous list in c#

Im not at a VS instance but it seems like this would work.

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


Related Topics



Leave a reply



Submit