2
\$\begingroup\$

I have a custom SPList that has a field Assigned To, now I can add as many items as I want, and they can have same title and same User they are assigned to, but what I want is a script so that I only get the distinct number of user's email address, e.g. if a user is assigned to more then 1 item, I will get there email address just once, here is the code I wrote down but I don't think if its good enough.

using (SPSite site = new SPSite("www.local.com"))
    using (SPWeb web = site.OpenWeb())
    {
        SPList mySourceList = web.Lists["ListName"];

        SPQuery mySourceListQuery = new SPQuery();

        mySourceListQuery.Query =

            "<OrderBy><FieldRef Name='AssignedTo' />" +
                     "<FieldRef Name='Title' />" +
            "</OrderBy>";



        SPListItemCollection mySourceItemColl = mySourceList.GetItems(mySourceListQuery);


        foreach (SPUser user in web.Users)
        {
            foreach (SPListItem mySourceListItem in mySourceItemColl)
            {
                name = mySourceListItem["AssignedTo"].ToString();

                name = name.Substring(name.IndexOf("#") + 1);

                if (user.Name == name)
                {
                    Console.WriteLine(user.Email);
                }
            }
        }
\$\endgroup\$
2
\$\begingroup\$

As written, your code will process each item in mySourceItemColl for every user in the site. I would prefer to only go through the collection one time.

As such, I would write it more like this:

using (SPSite site = new SPSite("www.local.com"))
    using (SPWeb web = site.OpenWeb())
    {
        SPList list = web.Lists["ListName"];
        SPQuery query = new SPQuery();
        query.Query =
            "<OrderBy><FieldRef Name='AssignedTo' />" +
                "<FieldRef Name='Title' />" +
            "</OrderBy>";
        SPitemCollection items = list.Getquery(query);
        List<string> emails = new List<string>();
        foreach (SPListItem item in items)
        {
            SPFieldUserValue value = 
                new SPFieldUserValue(web, item["AssignedTo"].ToString());
            if (null != value && 
                null != value.User && 
                !emails.Contains(value.User.Email)) 
            {
                emails.Add(value.User.Email);
                Console.WriteLine(value.User.Email);
            }
        }
    }
}
\$\endgroup\$
2
\$\begingroup\$
  1. The my prefixes are unnecessary, I'd call the variables sourceList, sourceListQuery, sourceItems etc.

  2. I'd create a method for this:

    name = name.Substring(name.IndexOf("#") + 1);
    

    I guess removeId could be a good name. The method name would help readers to understand the intent of the writer.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.