简体   繁体   English

如何在 C# 中使用 SingleOrDefault 创建用于从 Dictionary 查询值的谓词

[英]How can I create predicate for querying value from Dictionary using SingleOrDefault in C#

I have a Dictionary with Key as RectangleF and Value as int.我有一个字典,键为 RectangleF,值为 int。 Since, int will have duplicate values, So I cannot use that as key.因为 int 会有重复的值,所以我不能用它作为键。

Dictionary<RectangleF, int> lnRectTable = new Dictionary<RectangleF, int>();

lnRectTable.Add(new RectangleF(10.6f, 15.86f, 25.0f, 36.55f), 55);
lnRectTable.Add(new RectangleF(15.6f, 15.86f, 25.0f, 36.55f), 55);
lnRectTable.Add(new RectangleF(-36.8f, 15.86f, 25.0f, 36.55f), 150);

So, I want to find value "If Exists" in the Dictionary which matches the following condition.所以,我想在字典中找到符合以下条件的值“If Exists”。

RectangleF searchRect = new RectangleF(10.7f, 15.86f, 25.0f, 36.55f);

int matchingValue= lnRectTable.SingleOrDefault(
       t => Math.Abs(searchRect .X - t.Key.X) <= 0.1 &&
       Math.Abs(searchRect .Y - t.Key.Y) <= 0.1).Value;

//I will get value as 55. 

But, I want to use this kind of conditional check many times many places in my program.但是,我想在我的程序中多次使用这种条件检查。 What's the best way to do it.最好的方法是什么。 I am not sure, I am thinking of Predicates / Expressions.我不确定,我在考虑谓词/表达式。 So that I will more control.这样我会更有控制力。 If So, How do I do it ?如果是这样,我该怎么做?

Thanks in Advance.提前致谢。

You can assign your predicate to a variable or property and then use it everywhere.您可以将谓词分配给变量或属性,然后在任何地方使用它。

Func<RectangleF, RectangleF, bool> expr = 
  (RectangleF searchRect, RectangleF key) => 
     Math.Abs(searchRect.X - key.X) <= 0.1 && Math.Abs(searchRect.Y - key.Y) <= 0.1;

And then:进而:

int matchingValue= lnRectTable.SingleOrDefault(t => expr(searchRect, t.Key)).Value;

Or, if you want to get fancy you can partially-apply the searchRect to your function and then apply that:或者,如果您想花哨,您可以将 searchRect 部分应用于您的函数,然后应用它:

Func<RectangleF,bool> search = (RectangleF rect) => expr(searchRect, rect);

And then you can use the simpler syntax:然后你可以使用更简单的语法:

int matchingValue= lnRectTable.SingleOrDefault(search).Value;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM