Home > Software engineering >  LINQ - Simplify two lists by keeping index and removing items by condition
LINQ - Simplify two lists by keeping index and removing items by condition

Time:11-18

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.

CodePudding user response:

You can work with Enumerable.Zip() to combine both lists into one and then perform the filtering.

using System.Linq;

var combineList = list1.Zip(list2, 
        (a, b) => new { a = a?.ToString(), b = b?.ToString() })
    .Where(x => !String.IsNullOrEmpty(x.a)
        && !String.IsNullOrEmpty(x.b))
    .ToList();
        
list1 = combineList.Select(x => x.a).ToList();
list2 = combineList.Select(x => (object)x.b).ToList();

Demo @ .NET Fiddle

CodePudding user response:

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

  • Related