Add list to another one - nested list - c#

I would like to add some list to another list.
The result should looks like a main list contains nested list elements.
MainList:
[0]InnerList:
[0]some values
[1]some values
[1]InnerList:
[0]some values
[1]some values
I try to do this this way:
list.Add(new List<myClass>().Add(innerList));
but I've got an error message

Split it up, add does not return the list.
List<List<String>> inner = new List<List<String>>();
List<String> leaves = new List<String>();
leaves.Add( "some string" );
inner.Add( leaves );
list.Add( inner );

Try to use the list constructor instead of the Add method. Because the Add method returns void.
list.Add(new List<myClass>(innerList));
or if innerList is already of type List<myClass> then you can do:
list.Add(innerList);

List of elements of type myClass is List<myClass> so list of such lists is List<List<myClass>>. Here is a simple example how to create and populate such list of lists in one line (I used fictional type C):
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var list = new List<List<C>>{
new List<C>{
new C(1),
new C(2)
},
new List<C>{
new C(3),
new C(4)
}
};
Console.WriteLine((list[0][0]).Value);
Console.WriteLine((list[0][1]).Value);
Console.WriteLine((list[1][0]).Value);
Console.WriteLine((list[1][1]).Value);
}
}
public class C
{
public int Value;
public C(int val)
{
this.Value = val;
}
}
This will give you output:
1
2
3
4

Related

how to find an item in c# list

public class LIST
{
public double num;
public double longi;
public double ux;
public double vy;
}
public static List<LIST> LIST1= new List<LIST>();
LIST L1 = new LIST();
L1.ux= // I take l1.ux from stream reader by reading a file and made this
for
L1.vy=.. the other parameters
L1.longi=..
L1.num=....
LIST1.Add(L1)
Here my problem is ı made a list that contains 4 parameters. But ı want to find just one parameter value for instance L1.num how can I take this value from a list?
var indexOfLISTObject = 1 //you need to know which object from LIST1 you want to use
var numParamOfLISTObject = LIST1[indexOfLISTObject].num;
Please Don't name your object LIST. It will create readability issues down the line for you. Name the object what a particular item in your list will represent.
To access a particular property from an item in list you can do following
List l1 = new list();
//Add items ...
//Print property from particular index
Console.WriteLine(l1[index].propertyname);
Put the paremeters inside a list one by one.
in your example you want the parameter num.
List parameterNum = new List();
parameterNum = l1.Select(x => x.Num).ToList();
parameterNum has now the list of Num from l1 list.
If you mean to find/search for a particular value, you could also use System.Linq. For example if you would like to find a member where num is set to 2, you could do this:
LIST1.Where(item=>item.num==2).FirstOrDefault()
According my Understanding If you want to Get objects that contain with specific parameter
then you can use this code
public static List<LIST> LIST1= new List<LIST>();
LIST L1 = new LIST();
var SearchedValue= List1.where(x=>x.num==L1.num).tolist();
if you want just L1.num value then you can use this line (if searched record will 1 then you should use this)
var SearchedValue= List1.where(x=>x.num==L1.num).FirstOrDefault().num;
you can use
LIST1[index].propertyname //index is index of list element and propertyname is the name of property you want to access

How can I cast a list to an observablecollection in c#?

I have a List that I want to cast to an ObservableCollection, this is my code
var list = Models.Lands.FromJson(responce.Result.ToString());
this.Lands = new ObservableCollection<Land>( list );
FromJson returns me a List<Models.Land>, and this.Lands is an ObservableCollection<Models.Land>.
new ObservableCollection<Models.Land>( list ) gives me the following error:
cannot convert from System.Collections.Generic.List<> to
System.Collections.Generic.IEnumerable<>,
I thought that the constructor was overloaded for a List<> object.
Try using the nongeneric var keyword.
List<Land> list =Models.Lands.FromJson(responce.Result.ToString());
var collection = new ObservableCollection<Land>(list);
I think you can do something like below to avoid your problem but still using a single line of code:
this.Lands = new ObservableCollection<Land>( list.ToArray<Land>());
but I'm not sure if that's an efficient way to do that.
Works in my browser: https://dotnetfiddle.net/VVB8YY
public static void Main()
{
var list = new List<String>{"a", "b", "c"};
var collection = new ObservableCollection<string>(list);
foreach (var value in collection)
{
Console.WriteLine(value);
}
Console.WriteLine("Hello World");
}

Setting a Property via Reflection in a copied List updates original list

I'm experiencing a problem in my C# code and I'm sure it has to do with the way I'm using reflection, but I'm not sure how to fix it.
To the best of my knowledge, if I have:
List1 = List<MyClass>
and use a syntax similar to
List2 = new List<MyClass>(List1);
Then List2 should be a copy of List1 and any updates made to it should not reflect in the original list.
That being the case, consider the following test code:
public class Fake
{
public string MyVal { get; set; }
}
public List<Fake> List1;
public List<Fake> List2;
public void UpdateClassTest()
{
List1 = new List<Fake>() {new Fake() { MyVal = "hello" } };
List2 = new List<Fake>(List1);
string propName;
System.Type type = typeof(Fake);
foreach (System.Reflection.PropertyInfo pi in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
{
propName = pi.Name;
List2.ForEach(f => pi.SetValue(f, "Good Bye"));
}
}
When I run this Both List1[0] and List2[0] get updated to "Good Bye", but I would assume List1 would not be affected by the changes I'm making to List2.
What am I doing wrong or not understanding here?
new List(List other) does not do a deep copy. When you modify the item at [0] it's modifying the original object, which exists in both lists.
See this other question about implementing ICloneable.
Copying the list means that the lists are different objects. The elements contained by the lists are still the same. For instance:
List1 = new List<Fake>() {new Fake { MyVal = "hello" } };
List2 = new List<Fake>(List1);
List2.Add(new Fake { MyVal = "hey" });
Console.WriteLine(List1.Length); // 1
Console.WriteLine(List2.Length); // 2
List2[0].MyVal = "hi";
Console.WriteLine(List1[0].MyVal) // hi

Return List With Multiple Elements

I'm struggling getting my head around returning a List that has multiple elements (PHP background - I'd use arrays for this in PHP).
I have a large string that I'm parsing in a WHILE loop. I want to return a List with pairs of elements. I've tried something like this:
static public List<string> getdata(string bigfile)
{
var data = new List<string>[] { new List<string>(), new List<string>() }; // create list to hold data pairs
While (some stuff)
{
// add element pair to List<data>
data[0].Add(this); // add element to list - 'this' is declared and assigned (not shown)
data[1].Add(that); // add element to list - 'that' is declared and assigned (not shown)
}
return data???; // <<-- This is where I'm failing. I can, of course, return just one of the elements, like return data[0];, but I can't seem to get both elements (data[0] and data[1]) together.
} // end getdata
I've reviewed some answers, but I'm missing something. I've tried several things syntactically for the return value, but no luck. Any help would be greatly appreciated. I hate asking questions, but I've spent some time on this and I'm just not finding what I want.
Change method declaration to:
static public List<string>[] getdata(string bigfile)
try with
static public List<string>[] getdata(string bigfile)
{
....
}
Or
But if you need to return list of string array, then change the method as
static public List<string[]> getdata(string bigfile)
{
List<string[]> data= new List<string[]>();
While (some stuff)
{
data.Add(this);
data.Add(that);
}
return data;
}
The problem there is you are returning a Collection of List so the return type is mismatching. Try this one,
var data = new List<string>();
while (some stuff)
{
data.Add("test0");
data.Add("test1");
}
return data;
I want to return a List with pairs of elements
If you want pairs, use pairs:
static public List<Tuple<string, string>> getdata(string bigfile)
{
var data = new List<Tuple<string, string>>(); // create list to hold data pairs
while (some stuff)
{
// add element pair
data.Add(Tuple.Create(a, b)); // 'a' is declared and assigned (not shown)
// 'b' is declared and assigned (not shown)
}
return data;
}

Replacing ArrayList with List<> in C#

I am using extensively ArrayList and having difficulty to use this List<>. I am using the EntitySpace ORM for doing DAL stuff. This thing works nicely BUT the issue is that I have to defined List<> with type of object which is complaining that it can't convert that.
I am appreciate your help.
Original using ArrayList:
public ArrayList Get()
{
TndCustomerTendersCollection collection = new TndCustomerTendersCollection();
collection.Query
.Select
(
collection.Query.CustomerTenderID,
collection.Query.CustomerTenderID,
collection.Query.CustomerTenderCode,
collection.Query.CustomerTenderName,
collection.Query.StartDate,
collection.Query.DueDate,
collection.Query.CompleteDate,
collection.Query.DateCreated,
collection.Query.LastDateModified
)
.Where
(
collection.Query.IsActive.Equal(true)
);
ArrayList list = new ArrayList ();
foreach (TndCustomerTenders item in collection)
{
list.Add(item);
}
return list;
}
After replacing with List
public List<Tender> Get()
{
TndCustomerTendersCollection collection = new TndCustomerTendersCollection();
collection.Query
.Select
(
collection.Query.CustomerTenderID,
collection.Query.CustomerTenderID,
collection.Query.CustomerTenderCode,
collection.Query.CustomerTenderName,
collection.Query.StartDate,
collection.Query.DueDate,
collection.Query.CompleteDate,
collection.Query.DateCreated,
collection.Query.LastDateModified
)
.Where
(
collection.Query.IsActive.Equal(true)
);
// HOW DO CONVERT THAT TO THAT LIST
List<Tender> list = new List<Tender>();
foreach (TndCustomerTenders item in collection)
{
list.Add(item);
}
return list;
}
TndCustomerTenders and Tender are two different types.
You need to either explicitly convert from TndCustomerTenders to Tender, or you need to define an implicit conversion.
List<Tender> list = new List<Tender>();
foreach (TndCustomerTenders item in collection)
{
//assumes conversion via constructor
list.Add(new Tender(item));
}
or
List<Tender> list = new List<Tender>();
foreach (TndCustomerTenders item in collection)
{
Tender t = new Tender() { foo = item.foo, bar = item.bar };
list.Add(t);
}
return collection.ToList<Tender>();
Change
public List<Tender> Get()
to
public List<TndCustomerTenders> Get()
and change
List<Tender> list = new List<Tender>();
to
List<TndCustomerTenders> list = new List<TndCustomerTenders>();
Or if you are using the latest framework,
var list = new List<TndCustomerTenders>();
Is this what you want?
.Where(collection.Query.IsActive.Equal(true)).Cast<Tender>().ToList()

Categories

Resources