Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 months ago.
Improve this question
Hi all I have a object like below
dynamic obj = new
{
Translations = new
{
test="",
}
};
In this code I need to add more like test="" in c#
expected output
dynamic obj = new
{
Translations = new
{
test="",
ds ="",
dsfd=""
}
};
How can I do that I tried with add key not worked
This work
dynamic obj = new
{
Translations = new Dictionary<string, string>
{
{ "test", "" },
}
};
obj.Translations.Add("ds", "");
obj.Translations.Add("dsfd", "");
This won't work
var obj = new
{
Translations = new
{
test="",
}
};
obj.Translations = new
{
test="",
ds="",
tedsfdst="",
}
Because anonymous type properties are read only and cannot be set. Also, you can't treat Translations as a dictionary and add new properties to it, unless you define it as dictionary.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
How can I read information from a dictionary to a text box?
var cities = new Dictionary<int, string>
{
{ 10, "New York" },
};
textBox1.Text = cities.Values[1];
Try instead to use the index that you created on the dictionary:
var cities = new Dictionary<int, string>
{
{ 10, "New York" },
};
textBox1.Text = cities[10];
Context
I have a List<T> of type Question.
Class Question, in turn, contains a List<Answer>.
Class Answer has a member called public Question Question { get; set; } which stores the question of which the answer is for.
I'm using the collection initialization syntax to add a Question item to the list and object initialization to create a new Question. While doing so, I'm also creating new Answer objects using the object initialization syntax(nested).
Problem
How do I set the Question member of the inner Answer class to refer to the enclosing Question object? I know the point at which an Answer is created, the Question is not even fully initialized. But is there any way to obtain the outer Question instance so that I can set it to the inner Answer.
Code
private List<Question> questions = new()
{
new Question
{
Id = 1,
Text = "Test Question 1",
Difficulty = QuestionDifficulty.Easy,
Answers =
{
new Answer { Id = 1, Question = [?] },
new Answer { Id = 2, Question = [?] } // What should replace [?] here?
}
}
};
You can't do it in the collection/object initialiser, but I'd argue that you shouldn't do it there in the first place. It's quite error-prone to handwrite what the corresponding question for each answer should be. You might forget to do that sometimes too.
I suggest that you add a custom setter for the Answers property in Question that also sets the answer's Question property:
private List<Answer> answers;
public List<Answer> Answers {
get => answers;
set {
// If you feel like it, you can also set the old answers' questions to null
answers = value;
foreach (var answer in answers) {
answer.Question = this;
}
}
}
Then in the object initialiser, initialise the answers' list, rather than just adding to it:
private List<Question> questions = new()
{
new Question
{
Id = 1,
Text = "Test Question 1",
Difficulty = QuestionDifficulty.Easy,
Answers = new List<Answer> // <--- here!
{
new Answer { Id = 1 },
new Answer { Id = 2 }
}
}
};
This compiles to something like:
var question = new Question();
...
var list = new List<Answer>();
var answer1 = new Answer();
answer1.Id = 1;
var answer2 = new Answer();
answer2.Id = 2;
list.Add(answer1);
list.Add(answer2);
question.Answers = list;
As you can see, the setter is called, and the answers' Question property will be set.
It is not possible. But you can set the question to all answers after you created them. Do not assign a value to the question property during your use of the collection initialization. In your constructor, you do the following:
foreach(var question in questions)
{
foreach(var answer in question.Answers)
{
answer.Question = question;
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
This is my controller:
string responseString = reader.ReadToEnd();
dynamic jsonData = JsonConvert.DeserializeObject(responseString);
var results = new List<Result>();
foreach (var item in jsonData.items)
{
results.Add(new Result {
Title = item.title,
Link = item.link,
Snippet = item.snippet,
});
db.Results.AddRange(results);
db.SaveChanges();
}
return View(results.ToList());
But I get this error:
Violation of PRIMARY KEY constraint 'PK_Result'. Cannot insert duplicate key in object 'dbo.Result'. The duplicate key value is (0).
The statement has been terminated.
How can I solve that?
var results = new List<Result>();
foreach (var item in jsonData.items)
{
results.Add(new Result {
Title = item.title,
Link = item.link,
Snippet = item.snippet,
});
db.Results.AddRange(results);
db.SaveChanges();
}
On the first line you have initialized new List.
Then on each enumeration of jsonData.items:
you add new instance of Result type to results list.
you add the whole collection to db.Results DbSet. Because of db.Results.AddRange.
I think that you wanted to have something like this:
var results = new List<Result>();
foreach (var item in jsonData.items)
{
var result = new Result {
Title = item.title,
Link = item.link,
Snippet = item.snippet,
};
db.Results.Add(result);
}
db.SaveChanges();
May be you should include primary key value in results.Add() method.
Here you are trying to add values for title, link and snippet.
I believe none of them is primary key.
That's why it takes default value(0) for primary key.
You can check primary key field in your database table and include that as well in results.Add() method.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
What is the best way to map the result of adds to Codes?
result.adds contains a string array:
string[] adds = new string[] { "A", "B", "C" };
Option 1:
var car = new Car()
{
Name = request.Name,
Codes = (result.adds != null) ? adds : new string[] { }
};
In my opinion option 1 seems strange with creating a new empty string array when the result is false. I also have my doubts about mapping within the object mapping itself. On the other hand, it's direct and fast.
Option 2:
if (result.adds != null)
{
adds = results.adds;
}
var car = new Car()
{
Name = request.Name,
Codes = adds
};
Option 2 null check seems overkill to define the code seperately. It could simply be included in the mapper.
Of the two options you've presented option #1 looks the cleanest. However, you can simplify it more if you can use the null coalescing operator:
var car = new Car()
{
Name = request.Name,
Codes = result.adds ?? Array.Empty<string>()
};
This will use an empty string array in results.add is null.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
C# Initialize Object With Properties of Another Instance
(A) I can do this...
var newRestaurant = new Restaurant();
newRestaurant.Cuisine = model.Cuisine;
newRestaurant.Name = model.Name;
(B) And I can write it this way...
var newRestaurant = new Restaurant() { Name = model.Name };
(C) But how come I can't write it like so...
var newRestaurant = new Restaurant() model;
(Q) Isn't (B) just an Object-Literal while (C) is an object instance?
Would love to know.
Thx
Isn't (B) just an Object-Literal while (C) is an object instance?
The short answer? No. C# doesn't use curly braces to represent object literals like JavaScript or similar languages do; C# uses curly braces to refer to blocks.
In the code
var newRestaurant = new Restaurant() { Name = model.Name };
the { Name = model.Name } part isn't an object literal, it's an initializer block. You can use a similar syntax to initialize collections like lists and dictionaries:
var myString = "string3";
var myList = new List<string>() { "string1", "string2", myString };
var myDictionary = new Dictionary<string, int>()
{
{ "string1", 1 },
{ "string2", 2 },
{ myString, 3 },
};
As you can see, the syntax of these blocks differs based on what sort of object is before them. This code is transformed by the compiler into
var myString = "string3";
var myList = new List<string>();
myList.Add("string1");
myList.Add("string2");
myList.Add(myString);
var myDictionary = new Dictionary<string, int>();
myDictionary.Add("string1", 1);
myDictionary.Add("string2", 2);
myDictionary.Add(myString, 3);
And in the case of your example, it's transformed into:
var newRestaurant = new Restaurant();
newRestaurant.Name = model.Name;
When you try and use model like var newRestaurant = new Restaurant() model;, the compiler has no idea what sorts of properties are in model or what you meant to do with them; are you trying to add to a list? Are you trying to copy all the properties? What does it do if all the properties in model don't match?
Further reading
Later versions of C# will have something called Records, which will have a similar feature to what you're describing (copying fields from one thing to another). You can read about them on the compiler's github page if you're interested, but it's pretty technical.