How to use Select with multiple lists?

FranK Duc 121 Reputation points
2021-06-08T14:08:09.17+00:00

Hello,

I tried to iterate from 2 different lists.

var listm = new List<double>();
 listm.Add(Close.GetValueAt(CurrentBar));

 var listf = new List<double>();
 listf.Add(nearclose);


  var resulto =
     from li in listm
     from lis in listf
     select li;

 foreach (var resul in resulto)
 {


 fibo2 = (resul - lowPrice0) / (Ncma - lowPrice0);

 Print("num"+resul);
 }

The Select part bugs me.

How can i select both li and lis. With strings i could do select $"{ li } { lis}";

What about a double?

Thank you

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,411 questions
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Viorel 121.3K Reputation points
    2021-06-08T15:02:14.08+00:00

    If you write:

    var resulto =
       from li in listm
       from lis in listf
       select new { li, lis };
    
    foreach( var resul in resulto )
    {
       Console.WriteLine( $"{resul.li} {resul.lis}" );
    }
    

    then you will obtain all of the combinations.

    Maybe you need this:

    var resulto2 = listm.Zip( listf, ( li, lis ) => new { li, lis } );
    
    foreach( var resul in resulto2 )
    {
       Console.WriteLine( $"{resul.li} {resul.lis}" );
    }
    

  2. Karen Payne MVP 35,561 Reputation points
    2021-06-08T15:05:31.327+00:00

    Here is a lambda example

    private static void Example()  
    {  
        var list1 = new List<double>() {1.1, 1.2, 1.3};  
        var list2 = new List<double>() {2.1, 2.2, 2.3};  
      
        var result = list1.Zip(list2, (n, w) => new  
        {  
            Value1 = n,   
            Value2 = w  
        });  
          
        foreach (var item in result)  
        {  
            Console.WriteLine($"{item.Value1} - {item.Value2}");  
        }  
      
    }  
    

    103448-figure1.png

    Another method

    using var enumerator1 = list1.GetEnumerator();  
    using var enumerator2 = list2.GetEnumerator();  
      
    while (enumerator1.MoveNext() && enumerator2.MoveNext())  
    {  
        var item1 = enumerator1.Current;  
        var item2 = enumerator2.Current;  
        Console.WriteLine($"{item1} - {item2}");  
    }  
    

  3. Karen Payne MVP 35,561 Reputation points
    2021-06-08T16:58:03.91+00:00

    In regards to

    I need both Values to be passed in the same equation to avoid:

    You need a container that holds both values or two variables as otherwise you can't do what you are after. Also, this is not part of the original question which is to iterate two list, nothing about calculations which I just answered.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.