linq inline string operation - string

I've a method that returns this exception.
LINQ to Entities does not recognize the method 'System.String stringCutter(System.String)' method, and this method cannot be translated into a store expression.
public List<ProductReqNoDate> GetRequestsQuery()
{
var query = (from r in db.talepler
select new ProductReqNoDate
{
talepEdenBirim = r.talepEdenBirim,
talepNo = r.talepNo,
talepTarihi = r.talepTarihi,
urunAdi = stringCutter((from p in db.urunler
where p.talepNo == r.talepNo
select p.urunAd).FirstOrDefault()) // <--This
}).AsQueryable();
return query.ToList();
}
string stringCutter(string txt)
{
return string.IsNullOrEmpty(txt) ? "" : txt.Length <= 30 ? txt : txt.Substring(0, 30) + "...";
}
when i use this string operations inline, it works. but its too long,
urunAdi = ((from p in db.urunler where p.talepNo == r.talepNo select p.urunAd).FirstOrDefault()).Length <= 30 ?
((from p in db.urunler where p.talepNo == r.talepNo select p.urunAd).FirstOrDefault()) :
((from p in db.urunler where p.talepNo == r.talepNo select p.urunAd).FirstOrDefault()).Substring(0, 30) + "..."
How can i refer (from p in db.urunler where p.talepNo == r.talepNo select p.urunAd).FirstOrDefault()) as txt maybe; so i can use stringCutter method inline like:
urunAdi=string.IsNullOrEmpty(txt) ? "" : txt.Length <= 30 ? txt : txt.Substring(0, 30) + "...";
Is there a way of shortening this code. , thanks

EF is trying to map the function stringCutter into SQL. Which it can't because it does not know about it. The inline version only uses functions that EF knows to map to SQL expressions/function.

IQueryable<> cannot convert your expression to be used with the back-end store. You need to bring a string into memory first, then you can use IEnumerable<>'s projection method to call your method, like this:
return (from r in db.talepler
select new // First, use an anonymous type to read the building blocks
{
r.talepEdenBirim,
r.talepNo,
r.talepTarihi,
urunAdiStr = (from p in db.urunler
where p.talepNo == r.talepNo
select p.urunAd).FirstOrDefault()
}
).AsQueryable()
.ToList() // Force the data into memory
.Select(anon => new ProductReqNoDate {
talepEdenBirim = anon.talepEdenBirim,
talepNo = anon.talepNo,
talepTarihi = anon.talepTarihi,
urunAdi = stringCutter(anon.urunAdiStr) // Now stringCutter is available
}).ToList();

Related

how to extract an integer range from a string

I have a string that contains different ranges and I need to find their value
var str = "some text x = 1..14, y = 2..4 some text"
I used the substringBefore() and substringAfter() methodes to get the x and y but I can't find a way to get the values because the numbers could be one or two digits or even negative numbers.
One approach is to use a regex, e.g.:
val str = "some text x = 1..14, y = 2..4 some text"
val match = Regex("x = (-?\\d+[.][.]-?\\d+).* y = (-?\\d+[.][.]-?\\d+)")
.find(str)
if (match != null)
println("x=${match.groupValues[1]}, y=${match.groupValues[2]}")
// prints: x=1..14, y=2..4
\\d matches a single digit, so \\d+ matches one or more digits; -? matches an optional minus sign; [.] matches a dot; and (…) marks a group that you can then retrieve from the groupValues property. (groupValues[0] is the whole match, so the individual values start from index 1.)
You could easily add extra parens to pull out each number separately, instead of whole ranges.
(You may or may not find this as readable or maintainable as string-manipulation approaches…)
Is this solution fit for you?
val str = "some text x = 1..14, y = 2..4 some text"
val result = str.replace(",", "").split(" ")
var x = ""; var y = ""
for (i in 0..result.count()-1) {
if (result[i] == "x") {
x = result[i+2]
} else if (result[i] == "y") {
y = result[i+2]
}
}
println(x)
println(y)
Using KotlinSpirit library
val rangeParser = object : Grammar<IntRange>() {
private var first: Int = -1
private var last: Int = -1
override val result: IntRange
get() = first..last
override fun defineRule(): Rule<*> {
return int {
first = it
} + ".." + int {
last = it
}
}
}.toRule().compile()
val str = "some text x = 1..14, y = 2..4 some text"
val ranges = rangeParser.findAll(str)
https://github.com/tiksem/KotlinSpirit

How to make where filter of createCriteria dynamic in Grails framework

I am doing search with Pagination in groovy For the sake of pagination in different pages, I put a count filter "where". I want to get colName here dynamically but for where filter we need to put a instance of the domain. Here, the domain is Release. Is there any other way to calculate count?
def search(Integer max, Integer offset) {
def searchText = params.searchText
def colName = params.colName
def ReleaseList
def ReleaseCount
params.max = params.max ? params.int('max') : 10
if (searchText) {
def rel = Release.createCriteria()
List<Release> releasesList = rel.list() {
eq(colName, searchText)
} as List<Release>
ReleaseList = releasesList
ReleaseCount = Release.where {
colName == searchText
}.count()
} else {
ReleaseList = Release.list(params)
ReleaseCount = Release.count()
}
render(template: 'grid', model: [ReleaseInstanceList: ReleaseList, ReleaseInstanceCount: ReleaseCount], searchText: searchText)
}
If you pass in the max parameter for the list() method it will return a PagedResultList instance, which is a wrapper around the items that also hold the totalCount of matching items.
PagedResultList releases = Release.where { colName == searchText }.list(max: 10)
int totalCount = releases.totalCount
This also works for CreateCriteria.

little problem on code for finding substring within string scala

I am currently working on a small code that should allow to tell if a given substring is within a string. I checked all the other similar questions but everybody is using predefined functions. I need to build it from scratch… could you please tell me what I did wrong?
def substring(s: String, t: String): Boolean ={
var i = 0 // position on substring
var j = 0 // position on string
var result = false
var isSim = true
var n = s.length // small string size
var m = t.length // BIG string size
// m must always be bigger than n + j
while (m>n+j && isSim == true){
// j grows with i
// stopping the loop at i<n
while (i<n && isSim == true){
// if characters are similar
if (s(i)==t(j)){
// add 1 to i. So j will increase by one as well
// this will run the loop looking for similarities. If not, exit the loop.
i += 1
j = i+1
// exciting the loop if no similarity is found
}
// answer given if no similarity is found
isSim = false
}
}
// printing the output
isSim
}
substring("moth", "ramathaaaaaaa")
The problem consists of two subproblems of same kind. You have to check whether
there exists a start index j such that
for all i <- 0 until n it holds that substring(i) == string(j + i)
Whenever you have to check whether some predicate holds for some / for all elements of a sequence, it can be quite handy if you can short-circuit and exit early by using the return keyword. Therefore, I'd suggest to eliminate all variables and while-loops, and use a nested method instead:
def substring(s: String, t: String): Boolean ={
val n = s.length // small string size
val m = t.length // BIG string size
def substringStartingAt(startIndex: Int): Boolean = {
for (i <- 0 until n) {
if (s(i) != t(startIndex + i)) return false
}
true
}
for (possibleStartIndex <- 0 to m - n) {
if (substringStartingAt(possibleStartIndex)) return true
}
false
}
The inner method checks whether all s(j + i) == t(i) for a given j. The outer for-loop checks whether there exists a suitable offset j.
Example:
for (
(sub, str) <- List(
("moth", "ramathaaaaaaa"),
("moth", "ramothaaaaaaa"),
("moth", "mothraaaaaaaa"),
("moth", "raaaaaaaamoth"),
("moth", "mmoth"),
("moth", "moth"),
)
) {
println(sub + " " + " " + str + ": " + substring(sub, str))
}
output:
moth ramathaaaaaaa: false
moth ramothaaaaaaa: true
moth mothraaaaaaaa: true
moth raaaaaaaamoth: true
moth mmoth: true
moth moth: true
If you were allowed to use built-in methods, you could of course also write
def substring(s: String, t: String): Boolean = {
val n = s.size
val m = t.size
(0 to m-n).exists(j => (0 until n).forall(i => s(i) == t(j + i)))
}
I offer the following slightly more idiomatic Scala code, not because I think it will perform better than Andrey's code--I don't--but simply because it uses recursion and is, perhaps, slightly easier to read:
/**
* Method to determine if "sub" is a substring of "string".
*
* #param sub the candidate substring.
* #param string the full string.
* #return true if "sub" is a substring of "string".
*/
def substring(sub: String, string: String): Boolean = {
val p = sub.toList
/**
* Tail-recursive method to determine if "p" is a subsequence of "s"
*
* #param s the super-sequence to be tested (part of the original "string").
* #return as follows:
* (1) "p" longer than "s" => false;
* (2) "p" elements match the corresponding "s" elements (starting at the start of "s") => true
* (3) recursively invoke substring on "p" and the tail of "s".
*/
#tailrec def substring(s: Seq[Char]): Boolean = p.length <= s.length && (
s.startsWith(p) || (
s match {
case Nil => false
case _ :: z => substring(z)
}
)
)
p.isEmpty || substring(string.toList)
}
If you object to using the built-in method startsWith then we could use something like:
(p zip s forall (t => t._1==t._2))
But we have to draw the line somewhere between creating everything from scratch and using built-in functions.

Need to cut a string(Table Name) from Query in c#

My String/Query looks like this
insert into Employee Values(1,2,'xxx');
update Employee2 set col1='xxx' where col2='yyy';
select * from Employee3;
I need to take/have TableName alone. Table name won't be constant it will be differed(Employee,Employee2,Employee3) according to DB. I'm new to C# please help me. Thanks in advance.
To get the name of a table from a query (or in this case, a string named 'sql'), try the following:
string sql = "select * from table ";
int index1 = 0;
int index2 = 0;
int currentIndex = 0;
int numSpaces = 0;
char[] chArray = sql.ToCharArray();
foreach (char c in chArray)
{
if (c == ' ')
{
numSpaces++;
if (numSpaces == 3)
index1 = currentIndex;
if (numSpaces == 4)
{
index2 = currentIndex;
break;
}
}
currentIndex++;
}
int length = index2 - index1;
string tableName = sql.Substring(index1, length);
MessageBox.Show(tableName);
Warning - this solution is based on finding the word between the 3rd and 4th space character. This limits you to have a very predictable query structure - more complicated queries may not work with this solution. Your query structure needs to be:
"select column_name1,column_name2,column_name3 from table "
Your query must not have spaces between columns and must have a space at the end aswell. Sorry for the limitations but its the best I can come up with ;)

How can I translate this Groovy function to C#?

I would like to translate to C# the following Groovy code
def find_perfect_numbers(def number) {
(2..number).findAll { x-> (1..(x/2)).findAll{ x % it == 0 }.sum() == x }
}
which I got from here.
This is what I have, but it's not ready yet, doesn't compile either. I don't understand the groovy code good enough.
public List<int> find_perfect_numbers(int number)
{
List<int> lst = new List<int>();
lst = 2.To(number).FindAll(x => (1.To(x/2)).FindAll( x % it == 0).Sum() == x);
return lst;
}
I can't translate the part x % it == 0 (because "it" is an index).
I want the C# code to look as much like the groovy function as possible. Specifically, the line lst = 2.To( .....
I don't want to use a different solution to find perfect numbers (I have another working function already). For me this is only about the syntax, not about a good "perfect numbers function".
It's OK to create new (extension) functions that help doing this, just like the To function I used:
For the To function above I have used this StackOverflow function:
Generating sets of integers in C#
and changed it a little so that it returns a List of int instead of an array of int
public static class ListExtensions
{
public static List<int> To(this int start, int end)
{
return Enumerable.Range(start, end - start + 1).ToList();
}
}
Can anyone help me?
=== Update ===
This is what I have now, but it's not working yet, I get
DivideByZeroException was unhandled at the part s.value % s.idx == 0:
lst = 2.To(number).FindAll(x => ((1.To(x / 2)).Select((y, index) => new {value = y, idx = index}).Where( s => s.value % s.idx == 0).Sum(t => t.value) == (decimal)x));
I found it myself.
lst = 2.To(number)
.FindAll(x => ((1.To(x / 2))
.Select((y, index) => new {value = y, idx = index+1})
.Where( s => x % s.idx == 0)
.Sum(t => t.value) == (decimal)x));
Not as pretty as the Groovy one, but it works.

Resources