Linq cross join query for nested List

怎甘沉沦 提交于 2019-11-29 17:46:23

You seem to have a structure, removing all other details:

  • Table has a collection of fields
  • Field has a collection of values

And want to have a result which is all values cross all fields. I would start with getting a collection of all values across all fields on its own (using two queries to get both loops):

var values = from v in (from f in Table.Fields select f.Values)
             select v;

And then do the join:

var res = from v in values
          from f in Table.Fields
          select new {
             Field = f,
             Value = v
          };

This should cover your master/child sample in the first post:

class Program
{
    static void Main(string[] args)
    {
        var listofInts = new List<List<int>>(3);
        listofInts.Add(new List<int>{1, 2, 3});
        listofInts.Add(new List<int> { 4,5,6 });
        listofInts.Add(new List<int> { 7,8,9,10 });

        var temp = CrossJoinLists(listofInts);
        foreach (var l in temp)
        {
            foreach (var i in l)
                Console.Write(i + ",");
            Console.WriteLine();
        }
    }

    private static IEnumerable<List<T>> CrossJoinLists<T>(IEnumerable<List<T>> listofObjects)
    {
        var result = from obj in listofObjects.First()
                     select new List<T> {obj};

        for (var i = 1; i < listofObjects.Count(); i++)
        {
            var iLocal = i;
            result = from obj  in result
                     from obj2 in listofObjects.ElementAt(iLocal)
                     select new List<T>(obj){ obj2 };
        }

        return result;
    }
}

Thanks for you immediate response I tried your approach but still not gettting values in tabluar format. Let me clear the details once again.

Let say

Field1 has Value11
Field2 has Value21
Field3 has Value31 and Value32
Field4 has Value41, Value42 and Value43

All these fields belong to single table.

Now after Cross join, the result should be like this as hown below.

Value11 Value21 Value31 Value41
Value11 Value21 Value31 Value42
Value11 Value21 Value31 Value43
Value11 Value21 Value32 Value41 
Value11 Value21 Value32 Value42
Value11 Value21 Value32 Value43

.......
------

etc.  

Thanks

Buzzy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!