Return List Using Select New in Linq

Return list using select new in LINQ

Method can not return anonymous type. It has to be same as the type defined in method return type. Check the signature of GetProjectForCombo and see what return type you have specified.

Create a class ProjectInfo with required properties and then in new expression create object of ProjectInfo type.

class ProjectInfo
{
public string Name {get; set; }
public long Id {get; set; }
}

public List<ProjectInfo> GetProjectForCombo()
{
using (MyDataContext db = new MyDataContext (DBHelper.GetConnectionString()))
{
var query = from pro in db.Projects
select new ProjectInfo(){ Name = pro.ProjectName, Id = pro.ProjectId };

return query.ToList();
}
}

Linq select to new object

Read : 101 LINQ Samples in that LINQ - Grouping Operators from Microsoft MSDN site

var x = from t in types  group t by t.Type
into grp
select new { type = grp.key, count = grp.Count() };

forsingle object make use of stringbuilder and append it that will do or convert this in form of dictionary

    // fordictionary 
var x = (from t in types group t by t.Type
into grp
select new { type = grp.key, count = grp.Count() })
.ToDictionary( t => t.type, t => t.count);

//for stringbuilder not sure for this
var x = from t in types group t by t.Type
into grp
select new { type = grp.key, count = grp.Count() };
StringBuilder MyStringBuilder = new StringBuilder();

foreach (var res in x)
{
//: is separator between to object
MyStringBuilder.Append(result.Type +" , "+ result.Count + " : ");
}
Console.WriteLine(MyStringBuilder.ToString());

Linq to return a new object with a selection from the list

In LINQ with the query-syntax:

return (from a in IDs
from b in a.Values
where b.Code == code
select (new A
{
ID = a.ID, Values = new List<B>
{
new B
{
Code = b.Code,
DisplayName = b.DisplayName
}
}
})).FirstOrDefault();

Linq select returning string instead of object

You can't write the lambda body as a single expression that does what you want, but you don't need to. You can put multiple statements in a lambda:

var languages = _languageService
.GetAll()
.Select(x => {
var lvm = (LanguageViewModel)new LanguageViewModel().InjectFrom(x);
lvm.Code = x.Code.ToUpper();
return lvm;
})
.ToList();

LINQ What does 'select new' do?

As previous answers have noted both methods return an anonymous type. To fully answer your question though: "What are the benefits of the second statement over the first?"

The first statement returns all of the fields of m as-is. If you have 7 "columns" then activeMembers will contain all of them and whatever data they contain.

In the second statement you're projecting the results into a custom anonymous object that has only 3 fields. Not only that but you can perform logic on the "source fields" before storing them in the anonymous object. This gives you much of the flexibility of storing them in a container class without you actually having to define that class in code.

You could also do select new SomeClass { } which would project your results into a predefined class container.

The following pseudo-code may or may not be helpful in understanding the difference:

var myQuery = from p in someContext.someTable
group p by p.someField into g
select new MyContainer {
Field1 = g.Sum(a => a.field1)
Field2 = g.Max(a => a.field2)
};

myQuery in the above is now a collection of MyContainer. If I had omitted the class MyContainer then it would be a collection of an Anonymous Type containing the fields that I specified. Obviously, the difference here is that MyContainer has to be defined elsewhere in your code whereas the anonymous class is built/defined for you at compile time. In:

var myQuery = from p in someContext.someTable
select p;

myQuery is an anonymous class containing all of the fields and their values in someTable.

How to return ICollectionobject from linq, when using select new object() {}

List<T> implements ICollection<T>.

You don't need to do anything.

Return Linq query results into List object

Select() and Where() will return IQueryable<T>, not List<T>. You've got to convert it to a List<T> - which actually executes the query (instead of just preparing it).

You just need to call ToList() at the end of the query. For example:

// There's no need to declare the variable separately...
List<AgentProductTraining> productTraining = (from records in db.CourseToProduct
where records.CourseCode == course.CourseCode
select records).ToList();

Personally I wouldn't use a query expression though, when all you're doing is a single Where clause:

// Changed to var just for convenience - the type is still List<AgentProductTraining>
var productTraining = db.CourseToProduct
.Where(records => records.CourseCode == course.CourseCode)
.ToList();

LINQ and how to return a list of a specific type

var result = (from dc in _context.DocClasses
join d in _context.Documents
on dc.DocClassID equals d.DocClassID
where dc.DocClassID != 0 && docIds.Contains(d.DocID)
let children = from p in _context.DocClasses
where dc.ParentID == p.DocClassID
select new Child {
ChildId = dc.DocClassID,
ChildDocClassName = dc.DocClassName,
ParentId = p.DocClassID,
ParentDocClassName = p.DocClassName
}
select children).SelectMany(c=>c).ToList();

Linq not returning values when using Select to new Object

  var y = (from e in db.FuelBenefits
where e.Active == true
select new FuelAmountEmployeeCycle
{
CycleId = 1,
EmployeeId = e.EmployeeId,
Amount = e.QuantityByCicle,
Balance = e.QuantityByCicle
});

This query isn't running until it reaches to the ToList() code.

You should write it like this:

 var y = (from e in db.FuelBenefits
where e.Active == true
select new FuelAmountEmployeeCycle
{
CycleId = 1,
EmployeeId = e.EmployeeId,
Amount = e.QuantityByCicle,
Balance = e.QuantityByCicle
}).ToList();


Related Topics



Leave a reply



Submit