包含用户和公司的C#列表按公司分开

时间:2015-08-04 15:46:52

标签: c# linq

我从AD获得了一个用户列表,现在我正在尝试按照他们工作的公司对它们进行排序,然后通过电子邮件将它们发送给该公司。

我的用户列表如

WSDA Jon Smith
WERT James Smith
WSDA Jim Smith
WEDJ Dave Smith
and so on...

我还有一份公司名单

WSDA
WERT
WEDJ
so on...

循环浏览用户列表并按公司分隔的最佳方式是什么?

List<string> msgBody = new List<string>();
List<string> stations = new List<string>();

            PrincipalContext AD = new PrincipalContext(ContextType.Domain, "domain.com");
            UserPrincipal u = new UserPrincipal(AD);
            PrincipalSearcher search = new PrincipalSearcher(u);
            DirectorySearcher searcher = new DirectorySearcher();
            DateTime lastLogon = new DateTime();

foreach (UserPrincipal result in search.FindAll())
            {
                lastLogon = result.LastLogon ?? DateTime.Now;
                TimeSpan difference = todayDate - lastLogon;


                if (difference.TotalDays > 90 && result.PasswordNeverExpires == false && result.EmailAddress != null)
                {
                    msgBody.Add(string.Format("{0} {1} {2} ", result.GetProperty("company"), result.DisplayName, result.LastLogon));

                    if(stations.Contains(result.GetProperty("company")) == false)
                        stations.Add(result.GetProperty("company"));
                }

                search.Dispose();
            }



public static String GetProperty(this Principal principal, String property)
    {
        DirectoryEntry directoryEntry = principal.GetUnderlyingObject() as DirectoryEntry;
        if (directoryEntry.Properties.Contains(property))
            return directoryEntry.Properties[property].Value.ToString();
        else
            return String.Empty;
    }

2 个答案:

答案 0 :(得分:2)

GroupBy就是出于这种情况。

var usersByCompany = users.GroupBy(u => u.CompanyName);
foreach(var grouping in usersByCompany)
{
    Console.WriteLine("Company: " + grouping.Key);
    foreach(var user in grouping)
    {
        Console.WriteLine("  User: " + user.Name);
    }
}

答案 1 :(得分:0)

如何首先使用(假设您的对象上有可用的电子邮件字段),您可以按公司分组,然后从每个组中选择第一条记录的电子邮件属性。

List<string> companyEmails = userListName.GroupBy(user => user.Company).Select(u => u.Email.First()).ToList();