![](/img/trans.png)
[英]C# list.Sort and CompareTo throw IndexOutOfRangeException
[英]DirectorySearcher SizeLimit and List.Sort producing unwanted results C#
我有一些代碼,需要使用用戶輸入字符串在Active Directory中進行搜索。 我限制了搜索返回的結果數(最多20個)。 然后,我按Active Directory創建的日期降序對結果進行排序。 但是,如果我在一個特定用戶(例如“ Smith”)上有20個以上的結果(例如100個),則我會獲得20個用戶(由於對結果的限制),按創建日期排序,但這是100個中的最后20個按創建日期排序,我需要前20個。如果刪除SizeLimit,則將以正確的排序順序獲得所有100個結果。 下面是我的代碼,不確定需要調整什么。
public void getADSearchResults(string searchString)
{
//Create list to hold ADUser objects
List<ADUser> users = new List<ADUser>();
string[] allUsers = searchString.Split(new Char[] { ',' }, userSearchLimit);
var json = "";
foreach (string name in allUsers)
{
//Connect to the root of the active directory domain that this computer is bound to with the default credentials; seems to cover employee and provider OUs at minimum
var rootDirectory = new DirectoryEntry();
DirectorySearcher adSearch = new DirectorySearcher(rootDirectory);
adSearch.Filter = "(&(objectClass=user)(anr=" + name + "))";
//LIMIT NUMBER OF RESULTS PER USER SEARCHED
adSearch.SizeLimit = 20;
// Go through all entries from the active directory.
foreach (SearchResult adUser in adSearch.FindAll())
{
DirectoryEntry de = adUser.GetDirectoryEntry();
string userName = "";
userName = adUser.Properties["sAMAccountName"][0].ToString();
string createdDate = "";
createdDate = adUser.Properties["whenCreated"][0].ToString();
ADUser aduser = new ADUser(userName, createdDate);
users.Add(aduser);
}
}
users.Sort((x, y) => DateTime.Parse(y.createdDate).CompareTo(DateTime.Parse(x.createdDate)));
json = new JavaScriptSerializer().Serialize(new { users = users });
//return json;
HttpContext.Current.Response.Write(json);
}
public class ADUser
{
public ADUser(string UserName, string CreatedDate)
{
userName = UserName;
createdDate = CreatedDate;
...
}
我想你在那里有一個邏輯上的錯誤。
我想您需要將此操作分為兩部分:
1)獲取整個文件和用戶。 2)如果有用戶之前出現過,請給評論者循環,如果是,請跳過其所有記錄,直到下一位用戶為止。
該問題可能與您要在單個操作中執行並且僅剪切20個第一條/最后一條記錄的事實有關。
祝好運
PS:您可以在其中放置一個用戶過濾器嗎? 我的意思是,列表中的整個文件經過用戶篩選之后?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.