Am I missing something about LINQ?

后端 未结 6 567
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-31 01:23

I seem to be missing something about LINQ. To me, it looks like it\'s taking some of the elements of SQL that I like the least and moving them into the C# language and usin

6条回答
  •  误落风尘
    2020-12-31 02:14

    Before:

    // Init Movie
    m_ImageArray = new Image[K_NB_IMAGE];
    
    Stream l_ImageStream = null;
    Bitmap l_Bitmap = null;
    
    // get a reference to the current assembly
    Assembly l_Assembly = Assembly.GetExecutingAssembly();
    
    // get a list of resource names from the manifest
    string[] l_ResourceName = l_Assembly.GetManifestResourceNames();
    
    foreach (string l_Str in l_ResourceName)
    {
        if (l_Str.EndsWith(".png"))
        {
            // attach to stream to the resource in the manifest
            l_ImageStream = l_Assembly.GetManifestResourceStream(l_Str);
            if (!(null == l_ImageStream))
            {
                // create a new bitmap from this stream and 
                // add it to the arraylist
                l_Bitmap = Bitmap.FromStream(l_ImageStream) as Bitmap;
                if (!(null == l_Bitmap))
                {
                    int l_Index = Convert.ToInt32(l_Str.Substring(l_Str.Length - 6, 2));
                    l_Index -= 1;
                    if (l_Index < 0) l_Index = 0;
                    if (l_Index > K_NB_IMAGE) l_Index = K_NB_IMAGE;
                    m_ImageArray[l_Index] = l_Bitmap;
                }
                l_Bitmap = null;
                l_ImageStream.Close();
                l_ImageStream = null;
            } // if
        } // if
    } // foreach
    

    After:

    Assembly l_Assembly = Assembly.GetExecutingAssembly();
    
    //Linq is the tops
    m_ImageList = l_Assembly.GetManifestResourceNames()
        .Where(a => a.EndsWith(".png"))
        .OrderBy(b => b)
        .Select(c => l_Assembly.GetManifestResourceStream(c))
        .Where(d => d != null)  //ImageStream not null
        .Select(e => Bitmap.FromStream(e))
        .Where(f => f != null)  //Bitmap not null
        .ToList();
    

    Or, alternatively (query syntax):

    Assembly l_Assembly = Assembly.GetExecutingAssembly();
    
    //Linq is the tops
    m_ImageList = (
        from resource in l_Assembly.GetManifestResourceNames()
        where resource.EndsWith(".png")
        orderby resource
        let imageStream = l_Assembly.GetManifestResourceStream(resource)
        where imageStream != null
        let bitmap = Bitmap.FromStream(imageStream)
        where bitmap != null)
        .ToList();
    

提交回复
热议问题