I'm sending a JSON object through PUT from angularJS to c#, which has a property name and a value.
I'm trying to loop for each property and read both name and the value, but it fails. I have succeed to read only the name or only the value though with the below code:
Newtonsoft.Json.Linq.JObject cbpcs = pricestopsale.cbPricegroups;
foreach (string pricegroupInfo in cbpcs.Properties().Select(p => p.Value).ToList())
{
// I want to be able to do something like this inside here
if(pricegroupInfo.Value == "Something") {
// do stuff
}
}
In my above example pricegroupInfo has the value, if i change .Select(p => p.Name).ToList()) i get the name of the property.
What can I do if i want to get both name and value inside my loop ?
Update 1: The property Name is unknown to me, it's generated dynamically so I dont know in advance the property name.
Update 2: I want to be able to compare the value and the name as a string inside the loop.
Try using an anonymous object in the select.
Newtonsoft.Json.Linq.JObject cbpcs = pricestopsale.cbPricegroups;
foreach (var pricegroupInfo in cbpcs.Properties().Select(p => new { p.Value, p.Name }).ToList())
{
// read the properties like this
var value = pricegroupInfo.Value;
var name = pricegroupInfo.Name;
if(pricegroupInfo.Value.ToObject<string>() == "foo")
{
Console.WriteLine("this is true");
}
}
Reference: JObject.Properties Method
Newtonsoft.Json.Linq.JObject cbpcs = pricestopsale.cbPricegroups;
foreach (var pricegroupInfo in cbpcs.Properties())
{
if(pricegroupInfo.Name == "propName" // your property name
&& pricegroupInfo.Value.ToString() == "something") { // your value
// do stuff
}
}
As you can see, it returns IEnumerable<JProperty> which use can iterate and make use of to get property Name and Value
Try this
foreach(var prop in cbpcs.GetType().GetProperties()) {
Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(foo, null));}
Related
Following the steps from this post, I have used the following code to modify just one custom property from a .xslm file (excel with macros):
var newProp = new CustomDocumentProperty();
newProp.VTInt32 = new VTInt32("1");
newProp.FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}";
newProp.Name = "CurrentVersionExported";
using (var document = SpreadsheetDocument.Open(excelPath, true))
{
var props = document.CustomFilePropertiesPart.Properties;
var prop = props.Where(p => ((CustomDocumentProperty)p).Name.Value == "CurrentVersionExported").FirstOrDefault();
// If the property exists, get the return value and then delete the property.
if (prop != null)
{
prop.Remove();
}
// Append the new property, and fix up all the property ID values.
props.AppendChild(newProp);
int pid = 2;
foreach (CustomDocumentProperty item in props)
{
item.PropertyId = pid++;
}
props.Save();
}
It works well but there are two things that I do not understand:
What is the pid? i believe it is the property ID, but I do not understand why it has to be 2 initially.
How should I know the initial format ID from my property? My excel does not have an XML schema so I have used the format ID from the post I linked before, I do not know if it is wrong or not to use that one.
I have a list that needs to have objects added or modified depending on if they already exist or not named countries. It contains Country type objects and they themselves contain a name, points and a Skier type object.
List<Country> countries = new List<Country>();
...inputs
string name= inputData[1];
if (find if a country with name exists inside countries list)
{
change the country
}
else
{
make new country
}
I have the other stuff figured out but I dont know what to put in the if.
countries.Any(c=>c.Name==name) will return you a Boolean true if name exists in the list, but you might be better swapping Any for FirstOrDefault and testing the result:
var country = countries.FirstOrDefault(c=>c.Name==name);
if(country == default)
//add
else
//update the properties of the `country` variable here
could you use first or default to check the list. if it is not there add it.
if (countries.FirstOrDefault(x => x.Name == name) == null){
countries.add(new Country{Name = name});
} else {
// change country
}
you can use List<T>.Exists(Predicate<T>) Method . Specifies whether the List<T> contains the specified value.
if(countries.Exists(a => a.Name == name))
{
//change properties
}
else
{
//add
}
everyone, I am trying to write code that checks if there is alias name show it and if there is not then show the full name
This is my data:
This is My Code for showing FullName:
var TopStudents = await GetTopStudentsFromDb(count);
var codes = TopStudents.Select(e => e.StudentCode).Distinct().ToList();
var Students = await GetStudeentByCode(codes);
foreach (var St in TopStudents)
{
St.StudentsName =
Students.FirstOrDefault(e => e.Code == St.StudentCode)?.NameMajor.Refine();
}
this code works and shows the name now I want to change it to show the alias name of the major what should I do?
I want to check if it has Alias name show it if it doesn't then show the name.
The best will be to add a property on you TopStudens type that uses the null null-coalescing operator ?? - like:
public class TopStudents {
[NotMapped] // not persisted in database.
public string AliasOrNameMajor => Alias ?? NameMajor;
}
and then do it this way:
foreach (var St in TopStudents)
{
St.StudentsName =
Students.FirstOrDefault(e => e.Code == St.StudentCode)?.AliasOrNameMajor;
}
I have a method that accepts a variable that has a list of properties connected to it. What I need to do is create a linq query that will flag the current variable coming in as missing an "address" and add it to a list.
public void Teachers(List<Teacher> teachers)
{
foreach (Name name in teachers)
{
int age = program.CalculateAge(name.BirthDate.Year);
Name address = FilterAddress(name);
// Output Teachers Name - First Name, Last Name
if (name.Type.Equals(Name.NameType.Teacher))
{
OutputToConsole(name.FirstName, name.LastName, age);
program.WriteAddress(name);
}
}
Console.WriteLine();
}
Above is the method that will add the current variable in foreach loop to the FilterAddress Method. Below is where the variable is being passed. This variable has a List property named "Address" that is connected to it. This address can be null. I need to select each name with an address of null and add it to a list. But as you guessed, my LINQ code below doesn't work and just breaks.
public Name FilterAddress(Name name)
{
var NullItems = name.Select(x => x.Addresses).OfType<Name>();
return NullItems;
}
public Name[] FilterAddress(Name name)
{
return name.Where(x => string.IsNullOrEmpty(x.Addresses))
.Select(x => x.Name)
.ToArray();
}
Only need to add the "if null" check in the query to return if Adresses is null.
var NullItems = name.Where(x => x.Addresses == null);
I am trying to loop through data that is passed to my view in a model object. I want to list out the property name and the property value of each of the model properties, even if they are null. I have been at this for a few hours and have tried googling it but cannot get any good examples that work.
I got this to list out all of the properties of the current object, however cannot get the values:
#model List<object>
#foreach (var obj in Model)
{
var properties = obj.GetType().GetProperties();
foreach (var property in properties)
{
string name = null;
var value = ""
try
{
name = property.Name;
value = property.GetType().GetProperty(property.Name).GetValue(property, null).ToString();
}
catch (Exception e)
{
<p>#e</p>
}
finally
{
<p>#name - #value</p>
}
}
And the controller code:
RootobjectPlayerData obj = JsonConvert.DeserializeObject<RootobjectPlayerData>(jsonstring);
List<object> list = new List<object>();
list.Add(obj.data.accountinfo);
list.Add(obj.data.accountinfo.statistics);
list.Add(obj.data.accountinfo.statistics.clan);
list.Add(obj.data.accountinfo.statistics.company);
list.Add(obj.data.accountinfo.statistics.all);
list.Add(obj.data.accountinfo.statistics.historical);
list.Add(obj.data.accountinfo.statistics.team);
return View(list);
I am able to do a break point and view all of the data within each of the objects, however I cannot get it to print out on screen.
First of all you are getting the property value incorrectly. You should get the value from the object you have, but not from the type of the property:
value = obj.GetType().GetProperty(property.Name).GetValue(obj, null)
Secondly, try to loop only through data that's not null:
#foreach (var obj in Model.Where(w => w != null))
Try getting the values from i, not x.
try
{
name = x.Name;
// Wrong
// value = x.GetType().GetProperty(x.Name).GetValue(x, null).ToString();
// Correct
value = x.GetValue(i, null).ToString();
}
catch (Exception e)
{
<p>#e</p>
}