I am using Json.net
I have created a JArray and parsing the id values from it like so -
JArray userData = JArray.Parse(response.Content);
foreach (JObject content in userData.Children<JObject>())
{
items.Add(content["id"].ToString());
}
However I was trying to also do this usig Linq -
var items = userData.Where(x => x["id"].ToString() != null).ToList();
This seems to be a faster way to do this, however the problem I am having is that using the first method only adds the id values as I wanted, the Linq option puts the entire data set into items when the condition is met.
How an I change my condition so that it only extracts the id values?
It seems like you actually want LINQ Select.
It allows you to get items by projecting each element of a sequence into a new form.
var items = userData.Select(x => x["id"].ToString()).ToList();
Related
String priceID = codeArray[0];
var priceResult = from PRICE_LIST in priceContext.PRICE_LIST
where PRICE_LIST.PRICE_ID == priceID
select new
{
PRICE_LIST.RETAIL,
PRICE_LIST.WHOLESALE
}.ToList();
I'm receiving a compile error that the anonymous type does not contain a definition for ToList() and I'm not sure why? I've seen many examples where queries are stored using this method. I can do priceResult.ToList(), but both the retail and wholesale price columns are in the same list element. So I can't get retail by selecting the first element ect. New to EF & LINQ and still on the learning curve.
You need to put the entire LINQ within parentheses like this:
var priceResult = (from PRICE_LIST in priceContext.PRICE_LIST
where PRICE_LIST.PRICE_ID == priceID
select new
{
PRICE_LIST.RETAIL,
PRICE_LIST.WHOLESALE
}).ToList();
otherwise it tries to make each new object to a list
I have a ID list as "100,1025,5341" and a objects list. I want to get the IDs which are not include in my object list.
as an example, lets assume that objects list contains both 100 and 5341 as a property (eg: ID). I want to get 1025 as my result. I know that this request make no sense but i want to get that somehow. I can easily use,
string idList = "100,1025,5341";
var objectList = _dataService.GetData();
var result = objectList.Any(item=> idList.Contains(item.ID));
to get the list items which are having given IDs. But i want get other way. I want get the IDs which are not exists in the list.
Use Except:
var ids= idList.Split(',').Select(int.Parse);
var result = objectList.Where(item=> ids.Contains(item.ID));
var r= objectList.Except(result);
If you want only the ids that are not include in your object list, then you can do the following
var ids= idList.Split(',').Select(int.Parse);
var r= ids.Except(ids.Where(i=> objectList.Any(item=> item.ID==i)));
It will get you Ids from idList which are not Ids of objectList. If I undestood correctly what you want...
var ids = objectList.Select(x=>x.ID).ToList();
var otherIdsList = idList.Split(',').Select(x=>int.Parse(x)).ToList().Where(x=> !ids.Contains(x)).ToList();
I'm using the last driver. My documents are of the form
{
"ItemID": 292823,
....
}
First problem: I'm attempting to get a list of all the ItemIDs, and then sort them. However, my search is just pulling back all the _id, and none of the ItemIDs. What am I doing wrong?
var f = Builders<BsonDocument>.Filter.Empty;
var p = Builders<BsonDocument>.Projection.Include(x => x["ItemID"]);
var found= collection.Find(f).Project<BsonDocument>(p).ToList().ToArray();
When I attempt to query the output, I get the following.
found[0].ToJson()
"{ \"_id\" : ObjectId(\"56fc4bd9ea834d0e2c23a4f7\") }"
It's missing ItemID, and just has the mongo id.
Solution: I messed up the case. It's itemID, not ItemID. I'm still having trouble with the sorting.
Second problem: I tried changing the second line to have x["ItemID"].AsInt32, but then I got an InvalidOperationException with the error
Rewriting child expression from type 'System.Int32' to type
'MongoDB.Bson.BsonValue' is not allowed, because it would change the
meaning of the operation. If this is intentional, override
'VisitUnary' and change it to allow this rewrite.
I want them as ints so that I can add a sort to the query. My sort was the following:
var s = Builders<BsonDocument>.Sort.Ascending(x => x);
var found= collection.Find(f).Project<BsonDocument>(p).Sort(s).ToList().ToArray();
Would this be the correct way to sort it?
Found the solution.
//Get all documents
var f = Builders<BsonDocument>.Filter.Empty;
//Just pull itemID
var p = Builders<BsonDocument>.Projection.Include(x => x["itemID"]);
//Sort ascending by itemID
var s = Builders<BsonDocument>.Sort.Ascending("itemID");
//Apply the builders, and then use the Select method to pull up the itemID's as ints
var found = collection.Find(f)
.Project<BsonDocument>(p)
.Sort(s)
.ToList()
.Select(x=>x["itemID"].AsInt32)
.ToArray();
I am going to ask a very basic question and probably a repeated one but I have a bit different situation.
I want to use "in" operator in Linq.
I have to get all the rows from table which has Id provided
by my array and returns the row if it has. How can I do it.
My array has
var aa="1091","1092","1093" and so on.
and my table uses these Ids as Primary keys
.I have to get all the rows whose Id is contained in the array and I do not want to use S.P.
You can use Enumerable.Contains,
var aa = new string[3] { "1091", "1092", "1093" };
var res = yourDataSource.Where(c => aa.Contains(c.ID));
IN statements are created by using Contains in your Where call. Assuming you use integers as IDs, you could write something like this:
var myArray=new[]{1091,1092,1094};
var myEntities=from entity in myTable
where myArray.Contains(entity.ID)
select entity;
I have a LINQ Statement. It searches an XML file. (See example below) There are certain nodes that are required to have information in them. (Not empty) The LINQ Statement returns the transactions that have nodes which are empty, because these are required.
XML File Example:
<OnlineBanking>
<Transactions>
<Txn>
<UserName>John Smith</UserName>
<CustomerStreet>123 Main</CustomerStreet>
<CustomerStreet2></CustomerStreet2>
<CustomerCity>New York</CustomerCity>
<CustomerState>NY</CustomerState>
<CustomerZip>12345</CustomerZip>
</Txn>
</Transactions>
</OnlineBanking>
LINQ Statement:
//Start LINQ statement
var transactionList =
from transactions in root.Elements(XName.Get("Transactions")).Elements().AsEnumerable()
where transactions.Elements().Any
(
el =>
String.IsNullOrEmpty(el.Value) &&
elementsThatCannotBeEmpty.Contains(el.Name)
)
select transactions;
My Question:
I have the required fields (ie. CustomerStreet, CustomerCity, etc) in a database table. Below I have hard coded the XName's that are required. However, I want this to be dynamic from the database.
var elementsThatCannotBeEmpty = new HashSet<XName>
{
XName.Get("CustomerStreet"),
XName.Get("CustomerCity"),
XName.Get("CustomerState"),
XName.Get("CustomerZip")
};
Here is how I am retrieving the fields that are required from the database:
List<Setting> settingList = SettingsGateway.SelectBySettingType("VerifyField");
foreach (Setting SettingValue in settingList)
{
string strSettingType = setting.SettingType;
}
How do I take my database result loop and dynamically add XName.Get values?
Thank you so much for your help!
You're trying to check whether Any() of the strings in settingList are empty:
if (settingList.Any(
name => String.IsNullOrEmpty(el.Element(name).Value)
)
There is an implicit conversion from string to XName, so you don't actually need to call XName.Get.
If you want to, though, you could write el.Element(XName.Get(name))