Can't use .Union all with Linq - linq-to-sql

I have a problem, can you help me.
var query = (from MONHOC in db.tbl_MONHOCs
where
(MONHOC.IS_DELETE != 1 ||
MONHOC.IS_DELETE == null) &&
MONHOC.ISBATBUOC == 1
select new
{
ID = ("MH_CHA_" + Convert.ToString(MONHOC.ID_MONHOC)),
ID_NAME = MONHOC.ID_MONHOC,
MA_MONHOC = MONHOC.MA_MONHOC,
NAME = MONHOC.TEN_MONHOC,
ID_PARENT = 0
}).Concat
(from MONHOC in db.tbl_MONHOCs
where
(MONHOC.IS_DELETE != 1 ||
MONHOC.IS_DELETE == null) &&
MONHOC.ISBATBUOC == 0
select new
{
ID = ("MH_CON_" + Convert.ToString(MONHOC.ID_MONHOC)),
ID_NAME = MONHOC.ID_MONHOC,
MA_MONHOC = MONHOC.MA_MONHOC,
NAME = MONHOC.TEN_MONHOC,
ID_PARENT = (int?) MONHOC.ID_MONHOC_CHA
}
);
Error
Error Compiling Expression: Error Compiling Expression:
'System.Linq.IQueryable' does not contain a
definition for 'Concat' and the best extension method overload
'System.Linq.ParallelEnumerable.Concat(System.Linq.ParallelQuery,
System.Collections.Generic.IEnumerable)' has some invalid
arguments Instance argument: cannot convert from
'System.Linq.IQueryable' to
'System.Linq.ParallelQuery'

The exception message "clearly" :) tells you that the types of the properties in the anonymous types don't match.
In the first part you have:
ID_PARENT = 0
In the second part:
ID_PARENT = (int?) MONHOC.ID_MONHOC_CHA
These properties should both either be int? or int.

Related

Lua nested Json, remove single occurs or list of occurs if multiple

So what I am trying to do here is for a given json_body which is decoded json into a table using cjson I want to remove a given element by a configurable value conf.remove.json, I feel I am pretty close but its still not working, and is there a better way? Is there a safe way to find the tables "depth" and then reach out like conf.remove.json= I.want.to.remove.this creates the behavior json_table[I][want][to][remove][this] = nil without throwing some kind of NPE?
local configRemovePath= {}
local configRemoveDepth= 0
local recursiveCounter = 1
local function splitString(inputstr)
sep = "%." --Split on .
configRemovePath={}
configRemoveDepth=0
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
configRemovePath[configRemoveDepth + 1] = str
configRemoveDepth = configRemoveDepth + 1
end
end
local function recursiveSearchAndNullify(jsonTable)
for key, value in pairs(jsonTable) do --unordered search
-- First iteration
--Sample Json below, where conf.remove.json = data.id and nothing happened. conf.remove.json=data.id
--{
--"data": {
-- "d": 2,
-- "id": 1
--}
--}
-- value = {"d": 2, "id": 1}, key = "data", configRemovePath[recursiveCounter] = "data" , configRemovePath ['data','id'] , configRemoveDepth = 2
if(type(value) == "table" and value == configRemovePath[recursiveCounter] and recursiveCounter < configRemoveDepth) then --If the type is table, the current table is one we need to dive into, and we have not exceeded the configurations remove depth level
recursiveCounter = recursiveCounter + 1
jsonTable = recursiveSearchAndNullify(value)
else
if(key == configRemovePath[recursiveCounter] and recursiveCounter == configRemoveDepth) then --We are at the depth to remove and the key matches then we delete.
for key in pairs (jsonTable) do --Remove all occurances of said element
jsonTable[key] = nil
end
end
end
end
return jsonTable
end
for _, name in iter(conf.remove.json) do
splitString(name)
if(configRemoveDepth == 0) then
for name in pairs (json_body) do
json_body[name] = nil
end
else
recursiveCounter = 1 --Reset to 1 for each for call
json_body = recursiveSearchAndNullify(json_body)
end
end
Thanks to any who assist, this is my first day with Lua so I am pretty newb.
This is the official answer, found a better way with the help of Christian Sciberras!
local json_body_test_one = {data = { id = {"a", "b"},d = "2" }} --decoded json w cjson
local json_body_test_two = {data = { { id = "a", d = "1" }, { id = "b", d = "2" } } }
local config_json_remove = "data.id"
local function dump(o) --Method to print test tables for debugging
if type(o) == 'table' then
local s = '{ '
for k,v in pairs(o) do
if type(k) ~= 'number' then k = '"'..k..'"' end
s = s .. '['..k..'] = ' .. dump(v) .. ','
end
return s .. '} '
else
return tostring(o)
end
end
local function splitstring(inputstr, sep)
if sep == nil then
sep = "%." --Dot notation default
end
local t={} ; i=1
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
t[i] = str
i = i + 1
end
return t
end
local function setjsonprop(json_object, path, newvalue)
local configarray = splitstring(path)
while (#configarray > 1) do
json_object = json_object[table.remove(configarray, 1)]
if(type(json_object) == "table" and #json_object > 0) then
local recursepath = table.concat(configarray, ".")
for _, item in pairs(json_object) do
setjsonprop(item, recursepath, newvalue)
end
return
end
end
json_object[table.remove(configarray, 1)] = newvalue
end
setjsonprop(json_body_test_one, config_json_remove, nil)
print(dump(json_body_test_one))

Passing a table as argument to function in Lua

I want to loop through different indexed tables by only passing the initial table as an argument.
I currently have this table:
local table = {
stuff_1 = {
categories = {},
[1] = {
name = 'wui',
time = 300
}
},
stuff_2 = {
categories = {'stuff_10', 'stuff_11', 'stuff_12'},
stuff_10 = {
categories = {},
[1] = {
name = 'peo',
time = 150
},
[2] = {
name = 'uik',
time = 15
},
[3] = {
name = 'kpk',
time = 1230
},
[4] = {
name = 'aer',
time = 5000
}
},
stuff_11 = {
categories = {},
[1] = {
name = 'juio',
time = 600
}
},
stuff_12 = {
categories = {},
[1] = {
name = 'erq',
time = 980
},
[2] = {
name = 'faf',
time = 8170
}
}
}
I wanted to make a recursive function to check if the name in any of those tables was equal to some certain thing and return a string.
The recursivity lies in the idea of updating this table with whatever ammount I'd like (or until a certain limit).
I don't understand exactly what's wrong since when I try:
for k, v in pairs(table) do
print(k, v, #v.categories)
end
It correctly prints:
stuff_2 table: 0x10abb0 3
stuff_1 table: 0x10aab8 0
But when passing the table as a parameter to the the function below, it gives this error:
[string "stdin"]:84: attempt to get length of field 'categories' (a nil value)
Function:
function checkMessage(table)
local i = 1
local message = ""
for k, v in pairs(table) do
if(#v.categories == 0) then
while(v[i]) do
if(v[i].name == 'opd') then
if(v[i].time ~= 0) then
message = "return_1"
else
message = "return_2"
end
end
i = i + 1
end
else
checkMessage(table[k])
end
end
return message
end
EDIT: The problem lies in not ignoring that when using pairs onto the table, this doesn't just have tables with a category subtable but it also has a table named category, if this is ignored then the problem is fixed.
You're recursing into subtables that don't have a categories field. Trying to access categories on them yields nil, which you then try to use the length operator on. Hence your error:
attempt to get length of field 'categories' (a nil value)
If you can't hand trace your app, put in more print statements or get a line level debugger.

Haskell--Defining function with Guards

I am fairly new to Haskell and am working on an assignment simulating checkers currently. I am having a bit of difficulty determining the proper method of conditionally checking an expression and updating the values of a tuple. I have a function called getPos that will return the Char at a specific location on the board to determine its state.
onemove :: (Int,[Char],[[Char]],(Int,Int)) -> (Int,[Char],[[Char]])
onemove (a,b,c,(d,e))
| e <= 0 =(a-30,b,c)
| e > 50 =(a-30,b,c)
| (((posTo == 'r') || (posTo == 'i')) &&((posFrom == 'w')||(posFrom == 'k'))) == 'true' =(a-20,b,c)
| (((posTo == 'w')||(posTo == 'k')) && ((posFrom == 'r') || (posFrom == 'i')))== 'true' =(a-20,b,c)
| otherwise = (1000,b,c)
where posFrom = getPos (d, c)
posTo = getPos (e,c)
Is it correct to use a function to define a variable within my where clause? I receive the following error on my last line:
parse error on input `='
Your immediate problem is mostly just caused by indentation. Guards need to be indented w.r.t the definition they're associated with.
onemove :: (Int,[Char],[[Char]],(Int,Int)) -> (Int,[Char],[[Char]])
onemove (a,b,c,(d,e))
| e <= 0 =(a-30,b,c)
| e > 50 =(a-30,b,c)
| (((posTo == 'r') || (posTo == 'i')) &&((posFrom == 'w')||(posFrom == 'k'))) =(a-20,b,c)
| (((posTo == 'w')||(posTo == 'k')) && ((posFrom == 'r') || (posFrom == 'i'))) =(a-20,b,c)
| otherwise = (1000,b,c)
where posFrom = getPos (d, c)
posTo = getPos (e,c)
Notice I also removed the == 'true' in your original code. That was wrong for three separate reasons.
Single quotes denote a Char. Double quotes for String.
You can't compare a Boolean value to a String just because that String
happens to say "true". You would have to say == True.
There's no reason to ever write bool == True, because that's
exactly the same as just writing bool.
Also, a, b, c, and (d,e) should probably all be separate arguments, not a single tuple. You lose all the advantages of currying that way.

Add where clause if not NULL

here is my query:
List<string> kwList = GetFilterKeywords(); // returns NULL none keyword selected
var res = from d in ctx.Books
where (kwList == null || kwList.Contains(d.Name))
select d;
Looks like it is not legit to add where clause if kwList is NULL. So my question is: Is there any way to add more where clauses to the same query in IF/ELSE IF construction?
I mean:
var res = from d in ctx.Books
select d;
if (kwList != null)
{
res.Where(d => kwList.Contains(d.Name);
}
var res = ctx.Books; // no need to write select
if (kwList != null)
res = res.Where(x => kwList.Contains(x.Name));
foreach (d in res) {
...
}
You can use the tertiary operator
var res = kwList == null ? ctx.Books : ctx.Books.Where(x => kwList.Contains(x.Name));
If you want to modify the initial linq query in subsequent case statements, make sure to reassign the initial query to the modified:
var res = ctx.Books;
if (a == b)
{
// reassign here
res = res.Where(x => kwList.Contains(x.Name));
}
else if (a == c)
res = res.Where(x => x.Id == y);

LINQ2SQL A problem with return items based on a parameter

I occured a strange problem. I have that method
public static void ProcessCategories(int? myID)
{
var tmpList = Adapter.Category.Where(x => x.IdParentCategory == myID).ToList();
}
when myID == null (the parameter), the tmpList doesn't contain any elements, but if I type
x.IdParentCategory == null then some items are returned. Why ?
Try this:
public static void ProcessCategories(int? myID)
{
var tmpList = Adapter.Category.Where(x => x.IdParentCategory == myID || (myID == null && x.IdParentCategory == null)).ToList();
}