Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Linq c# simplify two list by keeping index and removing items that matches a null

I need to simplify two lists using linq keeping their index and removing pairs that might have a null/empty partner. Or if I could combine them into a dictionary of key-value pairs (int and decimal) that will also be great.

list1=["1","2","4","5","6"]
list2=["20.20","","",50.0,""]

to

list1=["1","5"]
list2=["20.20","50.0"]

I get the lists from a form collection of paymentcategory and amounts. The categories and amounts are dynamically generated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I have solution using loop.

    var data = new Dictionary<int, decimal>()
    if(lis1.Count==list2.Count)
    {
       for (var i = 0; i < list1.Length; i++)
       {
          if (!string.IsNullOrEmpty(list1[i])&&!string.IsNullOrEmpty(list2[i]))
            data.Add(Convert.ToInt32(list1[i]),Convert.ToDecimal(list2[i]));
       }
   }

now your data variable have Dictionary with int and decimal data.

Note: The both list needs to have same number of data otherwise it will through IndexOutOfRange exception

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading