开发者

C# lambda expression unable to manage a certain string compare

开发者 https://www.devze.com 2023-03-06 23:42 出处:网络
I have a specific lambda what doesn\'t seem to want to work properly although the logic seems sound. index = llCodeList.Find开发者_如何学JAVAIndex(f => string.Compare(f.Threshold.ToString(), searc

I have a specific lambda what doesn't seem to want to work properly although the logic seems sound.

index = llCodeList.Find开发者_如何学JAVAIndex(f => string.Compare(f.Threshold.ToString(), searchText, true ) >= 0);

f.Threshold is an integer value, it seems that the conversion doesn't happen and it breaks my search function. Can anyone shed some light on this?


Why not ditch the string compare and explicitly check?

index = llCodeList.FindIndex(
            f => f.Threshold.ToString()
                            .Contains(searchText));

Are you sure that the search text is a subset of the threshold number?

Also it may be that you're not understanding how string.Compare works, it won't check numerical value but string value. For the above if searchText is 4 and the threshold is -40 would match your predicate. My example more explicitly demonstrates the behavior of string.Compare(...,...,...) >= 0

If you're trying to find results based on having a greater than or equal to match on threshold and searchText you could do this

int search = 0;
int32.TryParse(searchText, out search);
index = llCodeList.FindIndex(f => f.Threshold >= search);


If my comment correctly got the gist of what you are trying to do then do something like this:

int index = -1;
int intVal;
if (int.TryParse(seachText, intVal)){
  index = llCodeList.FindIndex(f => f.Threshold >= intVal);
}


I think you meant to check IndexOf instead of using Compare.

index = llCodeList.FindIndex(
    f => f.Threshold.ToString().IndexOf(
        searchText, StringComparison.InvariantCultureIgnoreCase) >= 0);

But the name FindIndex sounds like you'd want to return the actual index. My crystal ball says you're looking for something like

index = llCodeList.FindIndex(
    f => f.Threshold.ToString().IndexOf(
        searchText, StringComparison.InvariantCultureIgnoreCase));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号