English 中文(简体)
LINQ 查询标有最接近的数据变量,以查询输入变量
原标题:LINQ query finding object with closest data variable to query input variable
  • 时间:2012-05-16 13:46:58
  •  标签:
  • c#
  • linq
  • min

I have a List where UserObj has a DateTime data member and a string Name member. I want to find the UserObj in the list with given Name InputName and with DateTime closest to an input DateTime InputDT

名称和日期可能同时发生,但将有一个独特的解决办法。

我认为:

UserObj user = userObjList.Where(u => ((u.Name ==inputName) && (userObjList.Min())).ToList()[0];

但不能确定如何规定最低条件?

最佳回答

两个日期之间的绝对差别使得这两个日期分开,然后是第一个。

UserObj user = userObjList
    .Where(u => u.Name == inputName)
    .OrderBy(u => Math.Abs((u.Date - inputDT).TotalSeconds))
    .First();

http://code.google.com/p/morelinq/source/browse/trunk/MoreLinq/MinBy.cs?r=83”rel=“nofollow” 延长:

UserObj user = userObjList
    .Where(u => u.Name == inputName)
    .MinBy(u => Math.Abs((u.Date - inputDT).TotalSeconds));
问题回答

我认为,以下工作虽然没有经过测试......

var validUserObjs = userObjList.Where(u => u.Name ==inputName);
double mintime = validUserObjs.Min(u=>Math.Abs((u.Date-inputDate).TotalSeconds));
var result = validUserObjs.First(u=>Math.Abs((u.Date-inputDate).TotalSeconds)==mintime);

想法是首先让用户获得有效的用户。 然后,委员会发现,最接近的日期是投入日期。 然后,委员会利用这一时间差异确定具体项目。

Its a lot messier than that given one with order by but it should be O(N) to do it (one pass through the list to find the minimum and then a second pass to get that item). It may need some minor tweaking for errors in my code but the idea is sound. :)





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签