Hi
I want to declare var Result once only. How it can be declared
C#
var Result = (from t2 in context.View_GroupParticipants
select new { t2.StudentID, Name = t2.Name + " - " + t2.MobileNo }).OrderBy(x => x.Name).Distinct().ToList();Thanks

Naimish MakwanaRank #324 · 7.7K reputationPosted Apr 9, 2023, 11:35 PM EDT
Hello Ramco,
you can define a named type for the objects returned by the LINQ query:
public class GroupParticipant { public int StudentID { get; set; } public string Name { get; set; } } // Declare the variable List Result; // Execute the LINQ query and assign the result to the variable Result = (from t2 in context.View_GroupParticipants select new GroupParticipant { StudentID = t2.StudentID, Name = t2.Name + " - " + t2.MobileNo }) .OrderBy(x => x.Name) .Distinct() .ToList();Thanks
Naimish Makwana
Jignesh KumarRank #91 · 22.9K reputationPosted Apr 9, 2023, 11:32 PM EDT
Hello Raco,
You can refer this link,
https://www.c-sharpcorner.com/Forums/how-to-initialize-implicit-variable
Tuhin PaulRank #7 · 71.9K reputationPosted Apr 9, 2023, 4:45 PM EDT
To declare the variable Result once only, you can use the var keyword to infer the type of the result of your LINQ query.
var Result = (from t2 in context.View_GroupParticipants select new { t2.StudentID, Name = t2.Name + " - " + t2.MobileNo }) .OrderBy(x => x.Name) .Distinct() .ToList();The var keyword is used to declare Result, and its type is inferred from the result of the LINQ query. The query is then chained with the OrderBy, Distinct, and ToList methods to sort, filter, and convert the result to a list.
The type of Result will be List, which is the type of the result of the LINQ query.
Naimish MakwanaRank #324 · 7.7K reputationPosted Apr 9, 2023, 11:30 PM EDT
Hello Ramco,
To declare the variable
Resultonly once, you can separate the LINQ query from the variable declaration and assign the result of the query to theResultvariable.// Declare the variable List Result; //You can declare it with class level. // Execute the LINQ query and assign the result to the variable Result = (from t2 in context.View_GroupParticipants select new { t2.StudentID, Name = t2.Name + " - " + t2.MobileNo }) .OrderBy(x => x.Name) .Distinct() .ToList();Thanks
Naimish Makwana
Ramco RamcoRank #462 · 5.4K reputationPosted Apr 9, 2023, 11:33 PM EDT
Hi Naimish
It gives error Cannot convert from system.collection.generic.list to system.collection.generic.list
Thanks