C# Instantiate List by Calling a Function - c#

Is there a more minimal way to write the following:
var voucherCodes = new List<string>();
for (int i = 0; i < 10; i++)
{
voucherCodes.Add(GenerateCode(VoucherCodeLength));
}
I would like to do something like this:
// ten items would be added to the list so long as GenerateCode returns a string
var voucherCodes = new List<string>(GenerateCode(VoucherCodeLength), 10);
Granted, I could create my own function, but I was wondering if there was something that already exists.

I can't say if it's better, but you can use the folloing LINQ "one-liner":
var voucherCodes = Enumerable.Range(0, 10).Select(_ => GenerateCode(VoucherCodeLength)).ToList();
or specifically for this call, and if the VoucherCodeLength is constant (or does not change and has no side effects), an even shorter:
var voucherCodes = Enumerable.Repeat(VoucherCodeLength, 10).Select(GenerateCode).ToList();

Another linqy way
var voucherCodes = Enumerable.Repeat(GenerateCode(VoucherCodeLength), 10).ToList();

Related

C# variable assignment

Can someone show me a simple way to assign variables.
I have many variables and not really know how to do, whether it be possible to use a loop?`
public void SwappingPlaces1()
{
Section_1[0] = Receiver_1[0];
Section_1[1] = Receiver_2[0];
Section_1[2] = Receiver_3[0];
Section_1[3] = Receiver_4[0];
Section_1[4] = Receiver_5[0];
Section_1[5] = Receiver_6[0];
Section_1[6] = Receiver_7[0];
Section_1[7] = Receiver_8[0];
Section_1[8] = Receiver_9[0];
Section_1[9] = Receiver_10[0];
Section_1[10] = Receiver_11[0];
Section_1[11] = Receiver_12[0];
Section_1[12] = Receiver_13[0];
Section_1[13] = Receiver_14[0];
Section_1[14] = Receiver_15[0];
Section_1[15] = Receiver_16[0];
Section_1[16] = Receiver_17[0];
Section_1[17] = Receiver_18[0];
Section_1[18] = Receiver_19[0];
Section_1[19] = Receiver_20[0];
Section_1[n] = Receiver_n[0];
...
}
You need to use reflection to get the names of the properties/fields by their name. Assuming Reciever_n is a property:
var properties = this.GetType().GetProperties();
for(int i = 0; i < n; i++)
{
var p = properties.Single(x => x.Name == "Receiver_" + i);
var value = p.GetValue(this, new object[] { 0 });
}
First you get all the properties defined on the type. Now you loop your list and get that single property with the name Receiver_ plus the current index.
Finally you invoke that property on the instance and provide the index of the indexed property (which is equal to zero here).
EDIT: However having so many properties with equal name and type seems a design-flaw, you should consider your actual design.
Thus a better appraoch might be to have just one single two-dimensional array Receiver.
You could add reference variables to an array and iterate over them. This is mostly usefull, clearing gui controls, like textboxes/labels etc.
var variables = new[] { Receiver_1, Receiver_2, Receiver_3, Receiver_4,
Receiver_5, Receiver_6 };
for(int i=0; i<Section_1.Length;i++)
Section_1[i] = variables[i][0];
But an index out of bounds is easely created
You could also use reflection.

Converting from one array to another array in C#

I've have this piece of code in C# which convert from one array to another:
IWebElement[] elements = Self.FindChildren()
Step[] steps = new Step[elements.Length];
for (int i = 0; i < elements.Length; i++)
{
steps[i] = new Step(elements[i]);
}
How can I write it in a shorter way (using linq or lambda expression) ?
Thanks
Omer
Linq approach
IWebElement[] elements = Self.FindChildren();
Step[] steps = elements.Select(x => new Step(x)).ToArray();
faster but without Linq
IWebElement[] elements = Self.FindChildren()
Step[] steps = new Step[elements.Length];
Array.Copy(elements, steps, elements.Length);

Table of strings in C#

Is there a way of creating a table with each cell containing a string in C# ?
The closest thing I found is multidimensional arrays string[,] names;, but it seems like its length needs to be defined which is a problem to me.
Here is what my code looks like :
string[] namePost;
int[] numbPage;
string post="";
string newPost;
int i=0;
int j=0;
foreach (var line in File.ReadLines(path).Where(line => regex1.Match(line).Success))
{
newPost = regex1.Match(line).Groups[1].Value;
if (String.Compare(newPost, post) == 0)
{
j = j + 1;
}
else
{
namePost[i] = post;
numbPage[i] = j;
post = newPost;
j = 1;
i = i + 1;
}
}
Each instance of the for writes the name of the new "post" in a cell of namePost. In the end, the namePost table stores the name of all the posts that are different from one another.
What is the best way to achieve that ?
If you are simply trying to store the posts, you can use the List class from the System.Collections.Generic namespace:
using System.Collections.Generic;
List<String> namePost = new List<String>();
Then, instead of namePost[i] = post;, use
namePost.Add(post);
DataTable
https://msdn.microsoft.com/en-us/library/system.data.datatable(v=vs.110).aspx
Use this, no need to define length at all.
Useful guide and examples:
http://www.dotnetperls.com/datatable
You can just use a
var table = new List<List<string>>();
This would give you a dynamic 2D table of strings.
This will give you all your unique posts. If you want the result as a list you can just do a
.ToList ()
with the result.
static IEnumerable<string> AllPosts(Regex regex, string filePath)
{
return File.ReadLines (filePath)
.Where (line => regex.Match (line).Success)
.Select (line => regex.Match (line).Groups [1].Value)
.Distinct ();
}

Concat not working - The underlying array is null

I am trying to Concat the two array IEnumerable lists and in result view it says The underlying array is null.
IEnumerable<ObjectToConcat> result = new ArraySegment<ObjectToConcat>();
var listA = new List<ObjectToConcat>();
var a = new ObjectToConcat
{OfficialId = Guid.NewGuid(), FirstName = "A Object"};
listA.Add(a);
var b = new ObjectToConcat
{OfficialId = Guid.NewGuid(), FirstName = "B Object"};
listA.Add(b);
// Error here is result view
result = result.Concat(listA);
var c = new ObjectToConcat
{OfficialId = Guid.NewGuid(), FirstName = "C Object"};
listB.Add(c);
// Error here is result view
result = result.Concat(listB);
Can anyone please suggest me what is wrong with my code. Or Concat does not work with List?
It would appear that this code:
IEnumerable<ObjectToConcat> result = new ArraySegment<ObjectToConcat>();
is an attempt to make an empty enumerable. You can do this more effectively and clearly by writing:
IEnumerable<ObjectToConcat> result = Enumerable.Empty<ObjectToConcat>();
That said, chaining a lot of Concat calls probably isn't the most effective, performance wise, if there are a lot of sub-lists. It's probably going to perform a bit better if you create a List<IEnumerable<ObjecToConcat>> allLists, add all of the sub-lists to that list, and then at the end you can write:
result = allLists.SelectMany(x => x);
to flatten it down to just a list of items.
you can have list of ObjectToConcat like below and add items to it using addrange method
List<ObjectToConcat> result = new List<ObjectToConcat>();
result.AddRange(listA);
Try this:
IEnumerable<ObjectToConcat> result =
new ArraySegment<ObjectToConcat>(new ObjectToConcat[0]).Array;

Method to check array list containing specific string

I have an ArrayList that import records from a database.
Is there any method to check whether the arrayList contains schname that i want to match to another list which is an api?
List<PrimaryClass> primaryList = new List<PrimaryClass>(e.Result);
PrimaryClass sc = new PrimaryClass();
foreach (string item in str)
{
for (int a = 0; a <= e.Result.Count - 1; a++)
{
string schname = e.Result.ElementAt(a).PrimarySchool;
string tophonour = e.Result.ElementAt(a).TopHonour;
string cca = e.Result.ElementAt(a).Cca;
string topstudent = e.Result.ElementAt(a).TopStudent;
string topaggregate = e.Result.ElementAt(a).TopAggregate;
string topimage = e.Result.ElementAt(a).TopImage;
if (item.Contains(schname))
{
}
}
}
This is what I have come up with so far, kindly correct any errors that I might have committed. Thanks.
How about ArrayList.Contains?
Try this
foreach( string row in arrayList){
if(row.contains(searchString)){
//put your code here.
}
}
Okay, now you've shown that it's actually a List<T>, it should be easy with LINQ:
if (primaryList.Any(x => item.Contains(x.PrimarySchool))
Note that you should really consider using foreach instead of a for loop to iterate over a list, unless you definitely need the index... and if you're dealing with a list, using the indexer is simpler than calling ElementAt.
// check all types
var containsAnyMatch = arrayList.Cast<object>().Any(arg => arg.ToString() == searchText);
// check strings only
var containsStringMatch = arrayList.OfType<string>().Any(arg => arg == searchText);

Categories