lundi 8 mai 2017

Find name of Variable in LINQ select statement

I am trying to find out which List<int> out of many has a certain amount of elements

Example input:

List<int> list_1 = Enumerable.Range(1, 299).ToList();
List<int> list_2 = Enumerable.Range(1, 300).ToList();
List<int> list_3 = Enumerable.Range(1, 300).ToList();
List<int> list_4 = Enumerable.Range(1, 297).ToList();

What I need is to log the name of the list and the amount of items if it has less than let's say 300 values. Now I could do of course a single if clause for every list:

if (list_1.Count != 300)
{
    //log name and number of items
}
if(list_2 ... and so on)

Question: Is there a more elegant way of finding out this information?

I tried a LINQ solution and put all Lists into one for filtering. But in this my problem is that I cannot get the name:

List<List<int>> allLists = new List<List<int>>();

allLists.Add(list_1);
allLists.Add(list_2);
allLists.Add(list_3);
allLists.Add(list_4);

string logRes = String.Join(" ", allLists.Where(x=>x.Count < 300)
        .Select(x=> String.Format("Name: {0} Amount: {1}", nameof(x), x.Count)));

It returns:

Name: x Amount: 299 Name: x Amount: 297

Question 2: How can I get the name of the evil list in the collection?

Aucun commentaire:

Enregistrer un commentaire