Linq to SQL select multiple columns - c#

I just want to select 2 columns from a MSSQL DB using LINQ.
The SQL should be
select table.col1,table.col2 from table
I tried
IList<string> myResults =
(
from data in dbconn.table
where table.col5 == null
select new {
col1=data.Id.ToString(),
col2=data.col2
}
).Take(20).ToList();
but this didn't work.
It says
cannot convert type list <AnonymousType#1> to Ilist<string>

You are basically trying to fill a list of strings with the entries of a list of anonymous types, that won't work.
Have you tried something like this?:
var list = from data in dbconn.table
where table.col5 == null
select new {
col1=data.Id.ToString(),
col2=data.col2
}
Then you can easily use the entries in a loop for example
foreach(var element in list) {
//...
}
Or like a list
list.Take(20).ToList();

First of all, a list of strings (List<string>) can only have one single string in an element not two (what you are trying to do here) changing the type to var would fix your exception but not sure if that is the solution you want.
var myResults =
(
from data in dbconn.table
where table.col5 == null
select new {
col1=data.Id.ToString(),
col2=data.col2
}
).Take(20).ToList();

You can select multiple fields using linq Select as shown above in various examples this will return as an Anonymous Type. If you want to avoid this anonymous type here is the simple trick.
var items = myResults.Select(f => new [] { f.Col1, f.Col2 }).SelectMany(item => item).Distinct();
I think this solves the problem

Related

C# query basic BSON knowing only key and values using LINQ

I have MongoDB collection from which I would like to query documents knowing only names of the keys.
I cannot use hardcoded base class because amount on keys will change over time in runtime. But as user I will know the names of them.
I tried doing it like that:
var collection = database.GetCollection<BsonDocument>(mongoCollectionName);
List<BsonDocument> list = (from c in collection.AsQueryable<BsonDocument>()
where c.GetElement("serial").Value == 1
select c).ToList();
but with that i get {document}.GetElement("serial").Value is not supported
So is there a way to use linq to query basic BSONs ?
Thanks !
Just make the viewModel same as the properties in MongoDb.
and For getting serial column whose value is 1, just do like this,
public class ViewModel {
.... model Properties goes here
}
var SerialNo = 1;
var collection = mongoDatabase.GetCollection<ViewModel>("name of your collection");
var builder = Builders<ViewModel>.Filter;
builder.Eq(x => x.serial, SerialNo );
Is it necessary to use LINQ? I mean it is not possible for you to do something like this?
var collection = database.GetCollection<BsonDocument>(mongoCollectionName);
List<BsonDocument> list = collection.Find(Builders<BsonDocument>.Filter.Eq("serial", 1)).ToList();
or even convert it to Dictionary.

Sequence contains several elements Dapper

I'm using Dapper for retrieve a result of my request SELECT.
List<dynamic> results = connection.Query("SELECT id_fonction from liste_personnels_fonctions where id_personnel = #id_personnel", new { id_personnel }).ToList();
But sometimes I have 2 results. When I use .SingleOrDefault() I have an exception : "Sequence contains several elements" when I have more than one row returned. When I use FirstOrDefault I have only first row and I need both of them...
So what can I do? I try with List<> and var[] to retrieve the results but it doesn't work.
Any ideas?
Thanks.
If you want just a list of Int then ask Dapper for that
List<int> results = connection.Query<int>("SELECT id_fonction from liste_personnels_fonctions where id_personnel = #id_personnel", new { id_personnel }).ToList();

Linq query with select needed to get specific properties from a list

I have a Linq query of which contains a List within a list. I thought I only wanted to have First record so I had the select part of my query written like this:
select new
{
EtchVectors = vio.Shapes.FirstOrDefault().Formatted
}).ToList();
This works great, it returns first record and the list that I have aliased "vio" has a list in it ( public List Shapes { get; set; } and Parse contains 2 properties, Formatted and Original. As I am rewriting this it seems I do not have access to "Formatted" if I get rid of FirstOrDefault()
This returns BOTH Formatted and Original obviously
EtchVectors = vio.Shapes
but, I cannot obviously do this:
EtchVectors = vio.Shapes().Formatted ( Shapes cannot be used like a method)
Should I be doing a different method or using a lambda ??
I think you are looking for a projection
EtchVectors = vio.Shapes.Select( s => s.Formatted );

LINQ2SQL: how to merge two columns from the same table into a single list

this is probably a simple question, but I'm only a beginner so...
Suppose I have a table containing home-work locations (cities) certain people use.
Something like: ID(int), namePerson(string), homeLocation(string), workLocation(string) where homeLocation and workLocation can both be null.
Now I want all the different locations that are used merged into a single list. Something like:
var homeLocation =
from hm in Places
where hm.Home != null
select hm.Home;
var workLocation =
from wk in Places
where wk.Work != null
select wk.Work;
List<string> locationList = new List<string>();
locationList = homeLocation.Distinct().ToList<string>();
locationList.AddRange(workLocation.Distinct().ToList<string>());
(which I guess would still allow duplicates if they have the same value in both columns, which I don't really want...)
My question: how this be put into a single LINQ statement?
Thanks in advance for your help!
var all = homeLocation.Union(workLocation).ToList();

Getting one list from another list using LINQ

I've seen the technique of taken a list of ObjectA and converting into a list of ObjectB where the two classes share some similar properties but is there an easier way to do that when you're just going from a list of ObjectA to another list of ObjectA?
Basically I want to do ...
var excv = from AuditedUser in data
where AuditedUser.IsMarkedForRemoval == false
select AuditedUser;
... but instead of a var I want the results to form a new List < AuditedUser > .
Is there something super easy I'm just missing?
var excv = (from AuditedUser in data
where AuditedUser.IsMarkedForRemoval == false
select AuditedUser).ToList();
I wrapped your LINQ statement with parens and added the ToList call at the end. Is this what you're looking for?
You could also do the following which is shorter to type and read I think:
List<AuditUser> excv = data.Where(a=>!a.IsMarkedForRemoval).ToList();

Categories

Resources