C# | Syntax to Initialize New Object With Properties of Another Instance [closed] - c#

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.

Related

insert a value to object add key was not worked [closed]

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.

delete empty entries tuple List String [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a Tuple List with 5 String values. This list contains about 250 entries with many empty entries.
How to delete these empty entries?
var program_list = new List<Tuple<string, string, string, string, string>>();
program_list.Add(Tuple.Create(program_name_String, publisher_name_String, program_version_String, install_location_String, uninstall_location_String));
I know how to delete these empty entries with a single String List. But this code won't work on Tuple List anymore.
program_names = program_names.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList();
program_names = program_names.Where(s => !string.IsNullOrEmpty(s)).Distinct().ToList();
program_names.Sort();
Thanks a lot.
I would suggest using a class rather than a tuple. Also you can still use it the same way you were using it for a string list. You just need to let it know to go deeper. Replace s with s.Item1 and you are set.
program_names = program_names.Where(s => !string.IsNullOrWhiteSpace(s.Item1)).Distinct().ToList();
but I suggest this:
public class myProgramClass
{
public string name, publisher_name, version, install_location, uninstall_location;
}
List<myProgramClass> program_list = new List<myProgramClass>();
myProgramClass new_entry = new myProgramClass() { name = "Name", publisher_name = "pub Name", version = "1.02", install_location = "dir", uninstall_location = "" };
program_list.Add(new_entry);
program_list = program_list.Where(s => string.IsNullOrWhiteSpace(s.name)).Distinct().ToList();

Which way is better to map a string array and null check? [closed]

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.

Put file name into list if it contains a certain number [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm starting to write a downloader.. But I want to put the files that need to extract, are required, or option in a list for later reference by the downloader.
A sample string that is fed into it would be like this:
file0.txt:0 file1.txt:0 file2.txt:1 file3.txt:2 file4.txt:2 file5.txt:2
What i want to do, is get an output like this:
Extract: file0.txt file1.txt
Required: file2.txt
Optional: file3.txt file4.txt, file5.txt
But I have no clue how to go about doing this.
The downloader will use these lists to download files the external app needs.
I'm assuming that the numbers that come after each file name are supposed to indicate what kind of file they are?
Now you definitely should try to solve this problem yourself - because thats how you learn, but here is a fairly elegant LINQ solution that creates an output identical to the example you posted.
// Define this in your class
enum FileType : byte
{
Extract = 0,
Required = 1,
Optional = 2,
}
static void Main(string[] args)
{
string input = "file0.txt:0 file1.txt:0 file2.txt:1 file3.txt:2 file4.txt:2 file5.txt:2";
// create list of files
var list = input.Split(' ').Select(file =>
{
var spl = file.Split(':');
var type = (FileType)Enum.Parse(typeof(FileType), spl[1]);
return new { Name = spl[0], Type = type };
}).ToArray();
// group by type and write to console
var group = list.GroupBy(l => l.Type);
foreach (var g in group)
{
Console.WriteLine("{0}: {1}", g.Key, String.Join(",", g.Select(a => a.Name)));
}
}
What you could do is two string split operations on the string you're fed.
var input = "file0.txt:0 file1.txt:0 file2.txt:1 file3.txt:2 file4.txt:2 file5.txt:2";
// gets each pairing
var filePairs = input.split(new[] {' '});
foreach(var filePair in filePairs)
{
var fileInfo = filePair.split(new[] {';'}); // [file0.txt, 0]
var fileName = fileInfo[0]; // file0.txt
var fileKeep = fileInfo[1]; // 0, 1, or 2.
}
From here you can do what you wish with the info you have in the foreach loop. And you can add the info to a list for storing it.

Copying a C# Collection to another collection [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have the following list/Collection which I need to copy into another list.But the list are not having the same number of parameters. But the name of the object and types are same. Here is the class
First Class:
public class Class1
{
int locationID{get;set;}
string locationName{get;set;}
}
Second Class:
public class Class2
{
int locationID{get;set;}
string locationName{get;set;}
string identifier{get;set;}
}
In my method, I need to get the value of the List1 and Copy the same to List2(Class2). List2 is having an extra parameter identifier.
How can this be implemented in C#??
If the types Class1 and Class2 are formally unrelated, the conversion has to be implemented manually, which can be done using Linq as follows.
var NewList
= OldList.Select(
x => new Class2{ locationID = x.locationID, locationName = x.locationName }
).ToList();
var l1 = new List<Class1>();
var l2 = new List<Class2>();
l2.AddRange(l1.Select(i=>new Class2() {locationID = i.locationID,
locationName = i.locationName});
Class1 and Class2 two are two different objects and signatures and cannot just be copied from one to another. What you will need to do is iterate over one list, crate a new object, copy the property values over, and add it to the other list.
var firstList = GetFirstList() //returns List<Class1>();
var secondList = new List<Class2>();
foreach(var first in firstList)
{
var second = new Class2();
second.locationID = first.locationID;
second.locationName = first.locationName;
//you could even set the identifier property here
second.identifier = someValue;
secondList.Add(second);
}

Categories