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);
}
Related
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 1 year ago.
Improve this question
Why is the object retrieved from the Dictionary by key not a reference?
My test code:
class Program
{
static Dictionary<int, Salad> test = new Dictionary<int, Salad>();
static void Main(string[] args)
{
test.Add(1, new Salad() { Vegetables = Vegetables.Tomato });
test.Add(2, new Salad() { Vegetables = Vegetables.Tomato });
var newSalad = new Salad() { Vegetables = Vegetables.Carrot };
test[1] = newSalad;
var salad2 = test[2];
salad2 = newSalad;
Console.WriteLine(test[1].Vegetables);
//Write: Carrot
Console.WriteLine(test[2].Vegetables);
//Write: Tomato
Console.ReadLine();
}
}
public class Salad
{
public Vegetables Vegetables { get; set; }
}
public enum Vegetables
{
Tomato,
Potato,
Carrot
}
You seem to be slightly confused as to how references in c# actually work.
When assigning a new value to a reference, you change the instance that reference points to, but any other references to that instance still points to the same instance.
salad2 and test[2] both starts as references to the same instance, but then you have this row: salad2 = newSalad;.
This row doesn't change the reference stored in the dictionary, it changes the salad2 reference and have it point to the same Salad instance that newSalad points to.
The test[2] reference is not changed.
If your code would have salad2.Vegetables = newSalad.Vegetables you would get Tomato in both Console.WriteLine() calls.
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();
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.
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 two lists of strings, illustrated as comma-separated below. How can I get the inverse of the intersection (i.e. all items that are only in one or the other list but not both?
For example:
string test1 = "word1,word2,word3,word4";
string test2 = "word2,word4";
In this example, I am looking for "word1" and "word3" since they each only occur in one list.
string test1 = "word1,word2,word3,word4";
string test2 = "word2,word4";
var result = string.Join(",", test1.Split(',').Except(test2.Split(',')));
public static void test()
{
string test1 = "word1,word2,word3,word4";
string test2 = "word2,word4";
List<string> test1list = test1.Split(',').ToList();
List<string> test2Lists = test2.Split(',').ToList();
List<string> result = new List<string>();
foreach (var item in test1list)
{
if (!test2Lists.Contains(item))
{
if (result.Any())
{
result.Add("," +item );
}
else
{
result.Add(item);
}
}
}
result.ForEach(p => Console.Write(p));
Console.ReadLine();
}
You can use a foreach loop and check whether the string value present in another; something like
string[] test1 = "word1,word2,word3,word4".Split(',');
string[] test2 = "word2,word4".Split(',');
foreach (var item in test1)
{
if (!test2.Contains(item))
Console.WriteLine(item);
}