Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq with embedded functions

Okay, so here's my question. I'm working with a saveresult from the Salesforce API, and I am learning LINQ. It may not be the best thing to use here, I don't know, but this is what I'm trying to do, just more eloquently.

BTW, here's the saveresult[] class shrunk down to definitions:

public partial class SaveResult {

    private Error[] errorsField;
    private string idField;
    private bool successField;

    [System.Xml.Serialization.XmlElementAttribute("errors")]
    public Error[] errors

    [System.Xml.Serialization.XmlElementAttribute(IsNullable=true)]
    public string id

    public bool success 
}

And here's waht I'm trying to do. Check for errors, return them if there are any in any of the returned save results, or return null if no errors.

string errors = null;
        foreach (SaveResult s in saved)
        {
            if (s.success) continue;
            else
            {
                foreach (Error e in s.errors)
                {
                    errors += String.Format("Errors on object: {0}. Error Code is: {1}. Error Message: {2}",
                                            s.id,e.statusCode.ToString(),e.message);
                }
            }
        }

So far I have:

return saved
   .Select(i => i.errors
      .Select(j => new { j.statusCode, j.message })
      .Distinct()
      .ToList()
      ).ToString();

I'm pretty sure I will need an anonymous function in there to evaluate i for errors before I go on.

Anyway, that's it. Thanks for the help (or the links pointing me to help!)

like image 326
Ryan Avatar asked Mar 08 '26 21:03

Ryan


1 Answers

Using the query syntax:

return string.Join("",
    from s in saved
    where ! s.Success
    from e in s.Errors
    select string.Format(
        "Errors on object: {0}. Error Code is: {1}. Error Message: {2}",
        s.id, e.statusCode);

This is translated to a SelectMany behind the scenes.

like image 124
Thom Smith Avatar answered Mar 10 '26 10:03

Thom Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!