How to add data from a list to a new[] - c#

I have a list o that has strings:
"Hist 2368#19:00:00#20:30:00#Large Conference Room",
"Hist 2368#09:00:00#10:30:00#Large Conference Room",
I want to add those strings to this:
var lines = new[]
{
"Meeting#19:00:00#20:30:00#Conference",
};
How would I use the data from the list o and insert it into lines?

Array are be nature, fixed-length. You need to create a new array, and assign it to lines.
lines = lines.Concat(o).ToArray();
Alternately,
lines = o.AddRange(lines).ToArray();
UPDATE: Fixed dumb mistake.

Since Lines is already an array, you'll need to merge the values into your list first:
foreach (var item in lines)
o.Add(item);
Then change o to an Array:
o.ToArray(); ///returns String[] with all three values.
You can also use .concat() as others have pointed out, which will internally do the same.

An additional thing to consider is the lines variable has an Array(T) type which is a fixed size, so you must either allocate enough space to hold all the data or copy the data into a new construct.
If you allocated enough space for lines to hold all the data then it looks something like this:
var o = new List<string>
{
"Hist 2368#19:00:00#20:30:00#Large Conference Room",
"Hist 2368#09:00:00#10:30:00#Large Conference Room",
};
var lines = new string[3] { "Meeting#19:00:00#20:30:00#Conference", null, null };
// Copy the data from o to the end of lines
o.CopyTo(lines, 1); // Start a 1 to not overwrite the existing data
See also:
CopyTo(T[] array)
Otherwise if you have two different data sources that you want to pool into a new construct then I recommend using the Concat method. This will combine the IEnumerable(T) types which you can use ToArray or ToList to give the data the right container.
var o = new List<string>
{
"Hist 2368#19:00:00#20:30:00#Large Conference Room",
"Hist 2368#09:00:00#10:30:00#Large Conference Room",
};
var lines = new[]
{
"Meeting#19:00:00#20:30:00#Conference",
}.Concat(o).ToArray();
Be sure you know which container you want to use.

You can concatenate the values using Enumerable.Concat :
lines = O.Concat(lines).ToArray();

Simply this
lines = lines.Concat(o).ToArray();

Try this:
List<string> myList = new List<string>()
{
"My First String in List",
"My Second String in List"
};
string[] myArray = new string[] { "My Array First String" };
List<string> myArrayList = new List<string>();
foreach (var item in myArray)
{
myArrayList.Add(item);
}
foreach (var item in myList)
{
myArrayList.Add(item);
}
foreach (var item in myArrayList)
{
Console.WriteLine(item);
}
Console.Read();

Related

How can I add the same value into multiple lists in one line?

I have two lists, l1 & l2
List<string> l1 = new List<string>();
List<string> l2 = new List<string>();
I want to put string.Empty into both of them in a single go.
We can do for variables like -
string a;
string b;
a = b = string.Empty;
I don't want to create List<List<string>>
Can anyone help me with it? thanks in advance.
I want to put string.Empty into both of them in a single go.
You cannot. You could make them point to the same list, but you cannot add into both lists at the same time. There also is no point to it. You don't gain anything. If you need this for anything but code aesthetics, please open a question containing your reasons to do this, because there is different concepts depending on what you want to achieve with it.
You can initialize the list with an empty string variable.
List<string> l1 = new List<string>() { string.Empty };
or something live this
string[] array = { string.Empty };
List<string> l1 = new List<string>(array);
List<string> l2 = new List<string>(array);
Either way, you will have same or less number of lines of code as you have now.
doing l1 = l2 will not work for Lists but you can do something like this
List<string> l2 = l1.ToList();
You can write a method that adds your item to two lists:
private void AddToTwoLists<T>(List<T> list1, List<T> list2, T item)
{
list1.Add(item);
list2.Add(item);
}
You can call it via
AddToTwoLists(l1, l2, string.Empty);
I don't want to create List<List<string>>
If you have only two lists you could do it without a two-dimensional array, but if you plan to have more of them at some point it would be a more convenient and scalable solution to use an array:
var l1 = new List<string>();
var l2 = new List<string>();
foreach (var list in new[] { l1, l2 })
list.Add(string.Empty);
It allows you to avoid writing Add for each list.
You can of course do something like this:
// Most comparable solution to:
string a;
string b;
a = b = string.Empty;
// is in my opinion this
List<string> list1, list2 = new List<string>(list1 = new List<string>{ string.Empty });
But to be honest I don't get your problem why you would do this.
This code is just creating two lists with one entry. And at the end it's the same result like:
List<string> list1 = new List<string>{ string.Empty }
List<string> list2 = new List<string>{ string.Empty }
Fully working example in dotnet fiddle

Get get part of list after certain value

I have got a simple question I am having a list:
List<string> test = new List<string> {"one", "two", "three", "four"}
Now I want to take for example value "three" and get all elements after it, so it would be looking like:
List<string> test = new List<string> {"three", "four"}
But we do not know where list end so it can be list of many elements and we can not define end as const.
Is it possible?
It sounds like you're looking for SkipWhile from LINQ:
test = test.SkipWhile(x => x != "three").ToList();
That will skip everything until (but not including) the "three" value, then include everything else. It then converts it to a list again.
Since you assign the filtered list back to initial one, then just remove first items up to "three" one:
int count = test.IndexOf("three");
test.RemoveRange(0, count < 0 ? test.Count : count);
This implementation doesn't create additional list, but modifies existing one.
This might do the trick for you
var list2 = test.Skip(2).Take(test.Count).ToList();
or better
var list3 = test.Skip(2).ToList();
Without LINQ it could be done something like this
List<string> outtest = new List<string>();
bool drty = false;
foreach(string st in test)
{
if(st == "three") //or whatever is the input.
drty = true;
if(drty)
outtest.Add(st);
}

Querying a list of strings with a query string?

I have a dictionary:
<string,List<string>>
The key is the product code say "product1" then the list is a list of properties:
"Brand","10.40","64","red","S"
Then I 'can' have a list of rules/filters e.g.
var tmpFilter = new customfilters();
tmpFilter.Field = "2";
tmpFilter.Expression = ">";
tmpFilter.Filter = "10";
So for the above example this would pass because at index 2 (tmpFilter.Field) it is more than 10; then I have another object which defines which fields within the list I want to write to file. For that dictionary item I just want to write the product brand and price where the filters match.
At the moment without the filter I have:
var tmp = new custom();
tmp.Columns = "0,1";
tmp.Delimiter = ",";
tmp.Extention = ".csv";
tmp.CustomFilters = new List<customfilters>() {new customfilters(){ Field = "2", Expression = ">", Filter = "10"} };
public static void Custom(custom custom)
{
foreach (var x in Settings.Prods)
{
//Get Current Product Code
var curprod = Settings.ProductInformation[x];// the dictionary value
foreach (var column in custom.Columns)
{
var curVal = curprod[Convert.ToInt32(column)];
tsw.Write(curVal + custom.Delimiter);
}
Settings.Lines++;
tsw.WriteLine();
}
tsw.Close();
}
I only want to write the curprod if all the filters pass for that list of strings.
How I can do this?
There's a really nice Nuget package based on an example published by Microsoft, that they have decided to make really hard to find for some reason, that allows dynamic linq queries:
https://www.nuget.org/packages/System.Linq.Dynamic/1.0.2
Source:
https://github.com/kahanu/System.Linq.Dynamic
Using that you can do stuff like this very easily (note: I used strings here because the OP states they have a List<string>):
List<string> stuff = new List<string> { "10.40", "64", "5", "56", "99", "2" };
var selected = stuff.Select(s => new { d = double.Parse(s) }).Where("d > 10");
Console.WriteLine(string.Join(", ", selected.Select(s => s.d.ToString()).ToArray()));
Outputs:
10.4, 64, 56, 99
That may give you a place to start. One thing you are going to have to tackle is identifying which of your fields are numeric and should be converted to a numeric type before trying to apply your filter. Otherwise you are going to comparing as strings.

check whether a List<string> contains an element in another List<string> using LINQ

How do I check whether a List contains an element that exists in another List using LINQ in C#? I don't want to use a for/while loop.
So, if List1 has A, B, C and List2 has B, 1, 2, then I would return true.
Try this:
List<string> a = ...
List<string> b = ...
var inComon = a.Intersect(b).Any();
Use Enumerable.Any Method:
List<string> l1 = new List<string> { "1", "2" };
List<string> l2 = new List<string> { "1", "3" };
var result = l2.Any(s => l1.Contains(s));
I'd say the Intersect method (see answer by dasblinkenlight) + Any must work better than Contains + Any. It is definetely better to use Any than Count.

Finding whether an element available in GenericList

I have a string[] which contains value {"data1","data2","data3"}.
and i have a GenericList which contains
data2
data4
two records
i want to get the common datas which is avail in string[] and the genericList
Have you tried something like
string[] s = {"data1", "data2", "data3"};
List<string> list = new List<string> { "data2", "data3" };
var commonList = list.Intersect(s);
Have a look at Enumerable.Intersect Method (IEnumerable, IEnumerable)
Assuming it's a List<string> and you're using .NET 3.5 or higher, you can use the Intersect method from LINQ to Objects:
var intersection = stringArray.Intersect(stringList);
Note that this will return a lazily-evaluated IEnumerable<string>. If you need it in an array or a list, call the relevant method:
var intersectionArray = stringArray.Intersect(stringList).ToArray();
// or
var intersectionList = stringArray.Intersect(stringList).ToList();
Also note that this is a set operation - so the result will not contain any duplicates, even if there is duplication of a particular element in both the original collections.
Take a look at the Intersect extension method here
string[] c1 = { "data1", "data2", "data3" };
string[] c2 = { "data2", "data4" };
IEnumerable<string> both = c1.Intersect(c2);
foreach (string s in both) Console.WriteLine(s);
Will print data2.

Categories