English 中文(简体)
如何看待我在林克收集中的目标[重复]
原标题:Neat way of gettings position of my Object in linq collections [duplicate]
  • 时间:2011-02-17 23:12:14
  •  标签:
  • c#
  • linq

我目前有一个称为周的物体。 一个星期是季节性物体的一部分。 季节可以控制许多星期。 我想做的是,我周(即季节的第一个星期(即1号))或是第二周(即2号)的立场。

int i = 0;
        foreach ( var w in Season.Weeks.OrderBy(w => w.WeekStarts)){
            if(w.Id == Id){
                return i;
            }
            i+=1;
        }

此时此刻,我已经这样做。 我宣布第二周开始,以确保它们符合正确的次序。 在我找到与我目前正在研究的一周相匹配的一周之前,我通过这些周。 并归还我所期望的原封不动。

I feel there should be a easier linq way to do this as it feels pretty messy!

最佳回答
问题回答

这里对一个非常相似的问题的答复:。 如何将某一要素的指数纳入计算方法?

很多答复与你已经采取的方式非常相似。 把逻辑推向分离关切和易于再利用的延伸方法,可能是一个好的想法。 The Marcgravell s Code from thelink above:

public static int IndexOf<T>(this IEnumerable<T> source, T value)
{
    int index = 0;
    var comparer = EqualityComparer<T>.Default; // or pass in as a parameter
    foreach (T item in source)
    {
        if (comparer.Equals(item, value)) return index;
        index++;
    }
    return -1;
}

SLaks在上张贴了一条子延伸方法。 IE amountables ,使你有办法从LINQ中找到指数:。 如何利用准则编制索引?





相关问题
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. ...

热门标签