Is it possible to use Take in LINQ when a query returns an anonymous type?

I am trying to get the nth element from the list of anonymous types returned by the LINQ query, where n is a random number from 0 to 100. Sent with it some time now, and I do not get anywhere. My code (with names changed to protect IP):

var query = from Table1 t1 in theContext.Table1 
   join Table2 t2 in theContext.Table2
    on ... 
    where ... 
   select new 
   {
       partNum = t1.part_number, 
       partSource = t2.part_source
   }

int num = new Random().Next(0, 100); 

// here where the code I've tried fails 

Is there any way I can do Take<T>(100).ToList<T>()[num]to get one anonymous type with partNum and partSource? I decided to solve this problem by explicitly defining the type, but it seemed to me that there was no more elegant solution. All I want to do is return it to the Dictionary<string, string>caller, so I would prefer not to define the type outside of this method.

Update : ElementAt does not work for this. I tried to add:

// get a random part from the parts list
int num = new Random().Next(0, query.Count() - 1 );
var nthElement = query.ElementAt(num);

And I got an exception: The query operator 'ElementAt' is not supported.

+3
2

:

var item = query.Take(100).ToList()[num];

, :

var item = query.Skip(num).First();
+6

, ElementAt :

var nthElement = query.ElementAt(num);

Take , , , ToList.

+3

Source: https://habr.com/ru/post/1707815/


All Articles