Entities to Linq Using lambda select clause

entity-framework linq-to-entities

Question

I am working on a new project and we are using Entity Framework and the dev lead would like to use lambda queries whenever possible. One thing we are having a hard time figuring out is how to select two columns specifically. Also how to select distinct. We have a table that has multiple entries for a vendor but we want to just get a list of vendors and load to a dictionary object. It fails because as written it is trying to add a key value that has already been added. Take the following query.

Dictionary<int, string> dict = new Dictionary<int, string>();
        dict = GetWamVendorInfo().AsEnumerable()
                    .Where(x => x.vendor_name != null && x.vendor_id != null)
                    //.Select(x => x.vendor_id).Distinct()
                    .Take(2)
                    .ToDictionary(o => int.Parse(o.vendor_id.ToString()), o => o.vendor_name);

What I would like to do is select just vendor_id and vendor_name so we can get just the distinct records.

Any help would be greatly appreciated.

Thanks,

Rhonda

1
5
9/2/2011 4:14:44 PM

Accepted Answer

Use an anonymous type:

// earlier bit of query
.Select(x => new { VendorId = x.vendor_id, VendorName = x.vendor_name } )
.Distinct()
.ToDictionary(o => o.VendorId, o => o.VendorName);

I've removed the call to Take(2) as it wasn't clear why you'd want it - and also removed the parsing of VendorId, which I would have expected to already be an integer type.

Note that you should almost certainly remove the AsEnumerable call from your query - currently you'll be fetching all the vendors and filtering with LINQ to Objects. There's also no point creating an empty dictionary and then ignoring it entirely. I suspect your complete query should be:

var vendors = GetWamVendorInfo()
                      .Select(x => new { VendorId = x.vendor_id,
                                         VendorName = x.vendor_name } )
                      .Distinct()
                      .ToDictionary(o => o.VendorId,
                                    o => o.VendorName);

As an aside, you should ask your dev lead why he wants to use lambda expressions (presumably as opposed to query expressions) everywhere. Different situations end up with more readable code using different syntax options - it's worth being flexible on this front.

9
9/2/2011 4:26:11 PM

Popular Answer

Just use an anonymous object:

var vendors = GetWamVendorInfo().AsEnumerable()
                .Where(x => x.vendor_name != null && x.vendor_id != null)
                .Select(new {x.vendor_id, x.vendor_name})
                .Take(2)

That's it. You can now work with vendors[0].vendor_id, vendors[0].vendor_name, and so on.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow