Select all rows but only specific columns - c#

Whats the linq+lambada expression to select all records in a table but only specific columns.
I tried something like the following which didnt work:
var Dc = new MyDataContext();
var mydata = Dc.TableA;
var newdata = mydata.Select(d => d (new {d.columnA,d.columnB,d.columnC}));

You were close - you have to project to an anonymous types with the columns you want:
var mydata = Dc.TableA.Select(d => new {d.columnA,d.columnB,d.columnC});

I think the issue you've got is a minor error in your code (in the example at least)
var Dc = new MyDataContext();
var mydata = Dc.TableA;
var newdata = mydata.Select(d => new {d.columnA,d.columnB,d.columnC});

var Dc = new MyDataContext();
var newdata = Dc.TableA.Select(d => new {d.columnA,d.columnB,d.columnC});

Related

How to select items using lambda expression

I am selecting data from a data store
I am able to fetch first array [0] {IHSWCFService.ServiceReference1.Observation} using below query
var newData = data.Select(a => new IHSData
{
PriceSymbol = Convert.ToString(a.PriceId),
PeriodData = Convert.ToDateTime(a.ObservationVector.Select(x => x.Period).FirstOrDefault()),
StatusID = Convert.ToInt32(a.ObservationVector.Select(x => x.StatusId).ToList()),
Price = Convert.ToDouble(a.ObservationVector.Select(x => x.price).FirstOrDefault()),
});
But I want to select next array also. as showing in below screen screenshot
[0]{IHSWCFService.ServiceReference1.Observation}
[1]{IHSWCFService.ServiceReference1.Observation}
[2]{IHSWCFService.ServiceReference1.Observation}
Could you please help me. Thanks
You might want all your properties in IHSData to be lists:
var newData = data.Select(a => new IHSData
{
PriceSymbol = Convert.ToString(a.PriceId),
PeriodData = a.ObservationVector.Select(x => Convert.ToDateTime(x.Period)).ToList(),
StatusID = a.ObservationVector.Select(x => Convert.ToInt32(x.StatusId)).ToList(),
Price = a.ObservationVector.Select(x => Convert.ToDouble(x.price)).ToList(),
});
Which is not such a good idea, because you have to index them separately. So another option would be to use SelectMany:
var newData = data
.SelectMany(a => a.ObservationVector.Select(v =>
new IHSData
{
PriceSymbol = Convert.ToString(a.PriceId), // parent PriceId
PeriodData = Convert.ToDateTime(v.Period),
StatusID = Convert.ToInt32(v.StatusId),
Price = Convert.ToDouble(v.price),
}))
.ToList();
The latter approach will create a separate IHSData instance for each ObservationVector, and some of them will share the same PriceId of the parent class.
Or, the third approach would be to have a new class, which would be the "parsed version of the ObservationVector", i.e. contain properties for parsed values, something like:
var newData = data.Select(a => new IHSData
{
PriceSymbol = Convert.ToString(a.PriceId),
Data = a.ObservationVector.Select(x => ConvertObservationVector(x)).ToList()
});
where ConvertObservationVector is a method which converts from an ObservationVector to your parsed class.

How do I find all collections with a certain string in the name in my MongoDB database?

I've got a database containing several collections. Some has got a name like "carpenter_title_year_version". Others has got a name like "plumber_title_year_version". How do I set up a filter to retrieve all collections where the string "carpenter" is in the collectionname?
I'm thinking something like:
var filterBuilder = Builders<GroupEntity>.Filter;
var projectionBuilder = Builders<GroupEntity>.Projection;
var collection = Database.GetCollection<GroupEntity>("dbname");
var filter = filterBuilder.ElemMatch("carpenter..., ?"); //<--- ???
var projection = projectionBuilder.Exclude("_id");
var list = await collection.Find(filter).Project(projection).ToListAsync();
There's (and an async version of it)
IAsyncCursor<MongoDB.Bson.BsonDocument> IMongoDatabase.ListCollections(ListCollectionsOptions options = null, CancellationToken cancellationToken = null);
You can use the filter from the collection options to match the collection name.
// <CAPS INSIDE> are wildcards
var _client = new MongoClient(#"connection string");
var _database = _client.GetDatabase("<DATABASE NAME>");
var bre = new BsonRegularExpression("<YOUR REGEX PATTERN>");
var copt = new ListCollectionsOptions{ Filter =
Builders<BsonDocument>.Filter.Regex ("name", bre )
};
var collectionsWithMatchingNames = _database.ListCollections(copt).ToList().Select (col => col["name"]);
Only then you get your particular collection, like:
foreach (var x in collectionsWithMatchingNames)
var collection = _database.GetCollection<BsonDocument>(x);

How to get result of rollup query for a custom entity

When trying to get the records I get this error
The 'Rollup' method does not support entities of type 'new_X'.
This is my code
RollupRequest req = new RollupRequest();
QueryExpression qe = new QueryExpression();
qe.EntityName = "new_x";
qe.ColumnSet = new ColumnSet(true);
req.Query = qe;
req.Target = new EntityReference("new_newpost", new Guid("xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"));
req.RollupType = RollupType.Related;
RollupResponse resp = (RollupResponse)xrm.Execute(req);
How can I get the results of rollup query
Thanks in advance
For custom entities you can do the fallowing
var rollupQuery = xrm.GoalRollupQuerySet.Where(c => c.Id == x.new_RecordstoRun.Id).First();
var result = xrm.RetrieveMultiple(new FetchExpression(rollupQuery.FetchXml));
But - How can I add a 'Skip' or 'Take' Linq to this?
You can only use the RollupRequest on a certain set of entities described on the MSDN.
So this will never work for "new_x" or "new_newpost".
This article has a correct demonstration of the RollupRequest using opportunity and account.
I would suggest just creating your own custom QueryExpression to retrieve all "new_x" and then link to "new_newpost" with LinkEntities.
Here is my code so get the results of RollupQuery
List<Guid> GetAllResultsFromRollupQuery(XrmServiceContext xrm, Guid rollupQueryId)
{
var rollupQuery = xrm.GoalRollupQuerySet.Where(v => v.Id == rollupQueryId).First();
var qa = GetQueryExpression(xrm, rollupQuery.FetchXml);
qa.PageInfo.Count = 1000;
qa.ColumnSet.AddColumn(rollupQuery.QueryEntityType + "id");
var result = new List<Guid>();
EntityCollection ec = null;
do
{
ec = xrm.RetrieveMultiple(qa);
ec.Entities.ToList().ForEach(v => result.Add((Guid)v.Attributes[rollupQuery.QueryEntityType + "id"]));
qa.PageInfo.PageNumber += 1;
} while (ec.MoreRecords == true);
return result;
}
QueryExpression GetQueryExpression(XrmServiceContext xrm, string fetchXml)
{
var req = new FetchXmlToQueryExpressionRequest { FetchXml = fetchXml };
var result = (FetchXmlToQueryExpressionResponse)xrm.Execute(req);
return result.Query;
}

Get a list of documents from Mongo DB

I want to do something like this:
List<int> fff = new List<int>();
fff.Add(1);
fff.Add(2);
fff.Add(5);
Mongo m = new Mongo();
m.Connect();
var dataBase = m.GetDatabase("database");
var collection = dataBase.GetCollection("coll");
IMongoQuery queryable = collection.AsQueryable();
MongoQueryProvider prov = new MongoQueryProvider(collection);
var query = new MongoQuery(prov);
var ffppp = from p221 in query where fff.Contains((int)p221["oid"]) select p221;
This throws this error : The method 'Contains' could not be converted into a constant.
I saw that mongo has an operator $in. Does any one know how can I use it from c#? (http://www.mongodb.org/display/DOCS/Advanced+Queries)
Thanks
After some more google-ing, I found this:
http://www.claassen.net/geek/blog/2009/09/linq2mongodb-building-linq-provider-for.html
var mongo = new Mongo();
var queryable = mongo["db"]["collection"].AsQueryable();
var in = from d in queryable where d.Key("foo").In("bar", "baz") select d;

Linq not in select on datatable

Hi i've got 2 data tables (bannedlist,countrylist), both contains list of country names and cods in columns cc and country. I am trying to do a query where i can select countries from countrylist table that are not in bannedlist table in order to create a 3rd table.
Any ideas?
I haven't got too far with this.
var ccList = ds.Tables[2].AsEnumerable();
var bannedCCList = ds.Tables[1].AsEnumerable();
var query = from r in ccList....
..
after trying
var bannedCCList = ds.Tables[1].AsEnumerable();
var query = from r in ccList where !bannedCCList.Any(b => b["cc"] == r["cc"])select r;
i still get same country list. banned ones haven't been removed. here is more detail in order to explain more. not sure what i am doing wrong
protected void BindCountryBan(string subd)
{
DataSet ds = new DataSet();
ds = new DB().CountryBan_GetSiteSettings();
BannedCountryListBox.DataSource = ds.Tables[1];
BannedCountryListBox.DataValueField = "cc";
BannedCountryListBox.DataTextField = "country";
BannedCountryListBox.DataBind();
//bind country list
var ccList = ds.Tables[2].AsEnumerable();
var bannedCCList = ds.Tables[1].AsEnumerable();
var query = from r in ccList where !bannedCCList.Any(b => b["cc"] == r["cc"])select r;
//var query = ccList.Except(bannedCCList);
//CountryListBox.DataSource = ds.Tables[2];
DataTable boundTable = query.CopyToDataTable<DataRow>();
CountryListBox.DataSource = boundTable;
CountryListBox.DataValueField = "cc";
CountryListBox.DataTextField = "country";
CountryListBox.DataBind();
}
Except would work if you use it on sequences of the countries:
using System.Linq;
...
var ccList = from c in ds.Tables[2].AsEnumerable()
select c.Field<string>("Country");
var bannedCCList = from c in ds.Tables[1].AsEnumerable()
select c.Field<string>("Country");
var exceptBanned = ccList.Except(bannedCCList);
If you need the full rows where the countries aren't banned, you could try a left outer join:
var ccList = ds.Tables[2].AsEnumerable();
var bannedCCList = ds.Tables[1].AsEnumerable();
var exceptBanned = from c in ccList
join b in bannedCCList
on c.Field<string>("Country") equals b.Field<string>("Country") into j
from x in j.DefaultIfEmpty()
where x == null
select c;
You can use the Except() LINQ extension method like this:
var result = full.Except(banned);
However this will work fine with the default comparer of the contained type. Thus if you want to use a specific column like in your example, you might need another approach like:
from r in ccList
where !bannedCCList.Any(b => b["cc"] == r["cc"])
select r;
Using Except() implies the references are the same in both collections, which I think is not the case with Tables, or correct me if I'm wrong.
Try this:
var query = ccList.Except(bannedCCList);

Categories

Resources