本文整理汇总了C#中Collection.Count方法的典型用法代码示例。如果您正苦于以下问题:C# Collection.Count方法的具体用法?C# Collection.Count怎么用?C# Collection.Count使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Collection
的用法示例。
在下文中一共展示了Collection.Count方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Save
public static long Save(string catalog, int officeId, int userId, long loginId, DateTime valueDate, string referenceNumber, string statementReference, Collection<OpeningStockType> details)
{
if (details == null)
{
throw new InvalidOperationException(Warnings.NoTransactionToPost);
}
if (details.Count().Equals(0))
{
throw new InvalidOperationException(Warnings.NoTransactionToPost);
}
string detail = CreateOpeningStockParameter(details);
string sql = string.Format(CultureInfo.InvariantCulture, "SELECT * FROM transactions.post_opening_inventory(@OfficeId::integer, @UserId::integer, @LoginId::bigint, @ValueDate::date, @ReferenceNumber::national character varying(24), @StatementReference::text, ARRAY[{0}])", detail);
using (NpgsqlCommand command = new NpgsqlCommand(sql))
{
command.Parameters.AddWithValue("@OfficeId", officeId);
command.Parameters.AddWithValue("@UserId", userId);
command.Parameters.AddWithValue("@LoginId", loginId);
command.Parameters.AddWithValue("@ValueDate", valueDate);
command.Parameters.AddWithValue("@ReferenceNumber", referenceNumber);
command.Parameters.AddWithValue("@StatementReference", statementReference);
command.Parameters.AddRange(AddOpeningStockParamter(details).ToArray());
long tranId = Conversion.TryCastLong(DbOperation.GetScalarValue(catalog, command));
return tranId;
}
}
示例2: Compare
public static void Compare(this Collection<Candidate> Collection, IEnumerable<Candidate> Items)
{
if (Items.Count() > 0)
{
Collection<Candidate> Temporary = new Collection<Candidate>();
foreach (Candidate c in Collection)
{
Temporary.Add(c);
}
Collection.Clear(); // Remove our items
bool bHasItems = (Temporary.Count() > 0) ? true : false;
foreach (Candidate c in Items) // For each item in our enumeration
{
if (bHasItems) // If our current collection has any items
{
foreach (Candidate e in Temporary) // For each item in our temporary collection
{
if (c.Id == e.Id) // If the Id is the same as the id in our items collection
Collection.Add(c); // Add to the current collection
}
}
else // If we have no items in our collection
Collection.Add(c); // Add all the items to our collection
}
}
}
示例3: FindAllRelationshipJson
/// <summary>
/// Find all objects related to the target object in any special relationship type.
/// </summary>
/// <param name="objectId"></param>
/// <returns></returns>
public System.Collections.ObjectModel.Collection<RelationshipObject> FindAllRelationshipJson(string objectId)
{
if (string.IsNullOrEmpty(objectId))
throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, "objectId cannot be empty"));
try
{
Collection<RelationshipObject> results = new Collection<RelationshipObject>(relationshipApi.FindAllRelationship(new Guid(objectId)).ToList());
if (results.Count() == 0)
return new Collection<RelationshipObject>();
return results;
}
catch (ArgumentException ex)
{
throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, ex.Message));
}
catch (BadRequestException bad)
{
throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, bad.Message));
}
catch (FormatException formatEx)
{
throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, formatEx.Message));
}
catch (Exception exp)
{
Logger.Instance(this).Error(exp);
throw new InternalServerErrorException();
}
}
示例4: CompactGenericTest
public void CompactGenericTest()
{
var collection = new Collection<TestClass>
{
null,
new TestClass(),
new TestClass(),
null,
new TestClass(),
null,
};
Assert.AreEqual(6, collection.Count);
Assert.AreEqual(3, collection.Count(tc => tc != null));
Assert.AreEqual(3, collection.Count(tc => tc == null));
var compactCollection = collection.Compact();
Assert.AreEqual(3, compactCollection.Count());
Assert.AreEqual(3, compactCollection.Count(tc => tc != null));
Assert.AreEqual(0, compactCollection.Count(tc => tc == null));
}
示例5: CompactStringTest
public void CompactStringTest()
{
const string notEmpty = "NOT_EMPTY";
var collection = new Collection<string>
{
null,
notEmpty,
notEmpty,
string.Empty,
"",
" ",
};
Assert.AreEqual(6, collection.Count);
Assert.AreEqual(3, collection.Count(string.IsNullOrEmpty));
Assert.AreEqual(3, collection.Count(tc => !string.IsNullOrEmpty(tc)));
var compactCollection = collection.Compact();
Assert.IsNotNull(compactCollection);
Assert.AreEqual(3, compactCollection.Count());
Assert.AreEqual(3, compactCollection.Count(tc => !string.IsNullOrEmpty(tc)));
Assert.AreEqual(0, compactCollection.Count(string.IsNullOrEmpty));
}
示例6: FindPath
public static List<Point> FindPath(int[,] field, Point start, Point goal)
{
//step 1
var closedSet = new Collection<PathNode>();
var openSet = new Collection<PathNode>();
//step 2
PathNode startNode = new PathNode()
{
Position = start,
CameFrom = null,
PathLengthFromStart = 0,
HeuristicEstimatePathLength = GetHeuristicPathLength(start, goal)
};
openSet.Add(startNode);
while (openSet.Count > 0)
{
//step 3
var currentNode = openSet.OrderBy(node =>
node.EstimateFullPathLength).First();
//step 4.
if (currentNode.Position == goal)
return GetPathForNode(currentNode);
//step 5.
openSet.Remove(currentNode);
closedSet.Add(currentNode);
//step 6.
foreach (var neighbourNode in GetNeighbours(currentNode, goal, field))
{
//step 7.
if (closedSet.Count(node => node.Position == neighbourNode.Position) > 0)
continue;
var openNode = openSet.FirstOrDefault(node =>
node.Position == neighbourNode.Position);
//step 8.
if (openNode == null)
openSet.Add(neighbourNode);
else
if (openNode.PathLengthFromStart > neighbourNode.PathLengthFromStart)
{
//step 9.
openNode.CameFrom = currentNode;
openNode.PathLengthFromStart = neighbourNode.PathLengthFromStart;
}
}
}
//step 10.
return null;
}
示例7: ListBranches
private void ListBranches(String GithubUrl)
{
ghc.Errors.Clear();
String[] urlparts = GithubUrl.Replace("https://", "").Replace("http://", "").Replace("/", "|").Split('|');
if (urlparts != null && urlparts.Length >= 3)
{
RepoOwner = urlparts[1];
Repository = urlparts[2];
branches = GetBranches(ghc, RepoOwner, Repository);
if (branches != null && branches.Count() > 0)
{
int idx = -1;
int selidx = -1;
if (curBranch == "")
{
selidx = 0;
}
foreach (Web.GithubJsonItem branchitem in branches)
{
idx++;
cmbBranch.Items.Add(branchitem.Name);
if (curBranch != "" && branchitem.Name == curBranch)
{
selidx = idx;
}
}
if (curBranch != "" && selidx == -1)
{
MessageBox.Show(String.Format(StringValue.BranchNotFound, curBranch));
selidx = 0;
}
cmbBranch.SelectedIndex = selidx;
cmbBranch.Enabled = true;
btnOK.Enabled = true;
cmbBranch.Focus();
btnRefresh.Enabled = true;
}
else
{
ShowInvalidUrl();
}
}
else
{
ShowInvalidUrl();
}
lblStatus.Text = StringValue.Ready;
}
示例8: see_if_we_get_a_not_disposed_warning
public void see_if_we_get_a_not_disposed_warning()
{
Repository repository = new Repository(_localDirectory_cloned);
var head = repository.Get<Commit>("HEAD");
var log = new Collection<Commit>();
Console.WriteLine(head.Message);
log.Add(head);
log.Add(head.Parent);
for (int i=0; i<log.Count(); i++)
Console.WriteLine(log.ElementAt(i).Message);
GitChangesetRepository gcr = new GitChangesetRepository(_localDirectory_cloned);
var testGet = gcr.Get(new ChangesetsAfterRevisionSpecification(65));
}
示例9: ObjectUserFollowingRepository
/// <summary>
/// Default constructor
/// </summary>
public ObjectUserFollowingRepository()
{
_userFollowings = new Collection<UserFollowingEntity>();
Random rnd = new Random();
IUserRepository userRepository = Repository.UserRepositoryInstance;
foreach (UserEntity user in userRepository.GetAll())
{
int followingCount = rnd.Next(1, userRepository.GetCount());
for (int i = 0; i < followingCount; i++)
{
int followingUserId = rnd.Next(1, userRepository.GetCount());
if (_userFollowings.Count(r => r.UserId == user.Id && r.FollowingId == followingUserId) == 0 && user.Id != followingUserId)
_userFollowings.Add(new UserFollowingEntity() { UserId = user.Id, FollowingId = followingUserId });
}
}
}
示例10: FindByKeywordJson
/// <summary>
/// Find all hierarchies which include the query keyword in code or name.
/// </summary>
/// <param name="hierarchyType"></param>
/// <param name="query"></param>
/// <param name="maxReturnedCount"></param>
/// <returns></returns>
public Collection<HierarchyDataObject> FindByKeywordJson(string hierarchyType, string query, int maxReturnedCount)
{
if (string.IsNullOrEmpty(hierarchyType))
throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, Resources.InvalidHierarchyType, hierarchyType));
try
{
int recordCount;
LinqPredicate predicate = new LinqPredicate("[email protected]", hierarchyType);
if (!string.IsNullOrEmpty(query))
predicate = predicate.Add("(Code!=null AND Code.StartsWith(@0)) OR (Name!=null AND Name.StartsWith(@0))", query.Replace("-", "").Trim());
IEnumerable<HierarchyDataObject> hierarchyDataObjects = hierarchyApi.FindHierarchyData(predicate, "Name ASC", 0, maxReturnedCount, out recordCount);
Collection<HierarchyDataObject> results = new Collection<HierarchyDataObject>();
IEnumerable<HierarchyDataObject> dummyRootHierarchyDataObjects = FindHierarchyDataObjectWithParentNotExist(hierarchyDataObjects);
foreach (HierarchyDataObject dummyRootHierarchyDataObject in dummyRootHierarchyDataObjects)
HierarchizeHierarchyData(hierarchyDataObjects, dummyRootHierarchyDataObject, results, 0);
if (results.Count() == 0)
return new Collection<HierarchyDataObject>();
return results;
}
catch (ArgumentException ex)
{
throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, ex.Message));
}
catch (BadRequestException bad)
{
throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, bad.Message));
}
catch (FormatException formatEx)
{
throw new BadRequestException(string.Format(CultureInfo.InvariantCulture, formatEx.Message));
}
catch (Exception exp)
{
Logger.Instance(this).Error(exp);
throw new InternalServerErrorException();
}
}
示例11: FindPath
public List<Cell> FindPath(GameField field, Cell start, Cell goal, Func<Cell, Cell, float> weightFunc = null)
{
var closedSet = new Collection<PathNode>();
var openSet = new Collection<PathNode>();
PathNode startNode = new PathNode()
{
Position = start,
CameFrom = null,
PathLengthFromStart = 0,
HeuristicEstimatePathLength = GetHeuristicPathLength(start, goal)
};
openSet.Add(startNode);
while (openSet.Count > 0)
{
var currentNode = openSet.OrderBy(node =>
node.EstimateFullPathLength).First();
if (currentNode.Position == goal)
return GetPathForNode(currentNode);
openSet.Remove(currentNode);
closedSet.Add(currentNode);
foreach (var neighbourNode in GetNeighbours(currentNode, goal, field, weightFunc))
{
if (closedSet.Count(node => node.Position == neighbourNode.Position) > 0)
continue;
var openNode = openSet.FirstOrDefault(node =>
node.Position == neighbourNode.Position);
if (openNode == null)
openSet.Add(neighbourNode);
else
if (openNode.PathLengthFromStart > neighbourNode.PathLengthFromStart)
{
openNode.CameFrom = currentNode;
openNode.PathLengthFromStart = neighbourNode.PathLengthFromStart;
}
}
}
return null;
}
示例12: UpdateDataTable
internal void UpdateDataTable(Collection<ReportData_Invoice> reportDataCollection, int startIndex)
{
EmptyTable();
TextBlock[,] textBlock2D = GetTextBlock2D();
if (reportDataCollection.Count() > 0)
{
try
{
for (int row = 0; row < 12; row++)
{
//Set INVOICE NUMBER
textBlock2D[row, 1].Text = String.Format("{0:00000000}", Int32.Parse(reportDataCollection[startIndex].GetInvoiceNumber()));
//Set TIME
textBlock2D[row, 2].Text = reportDataCollection[startIndex].GetTimeStamp();
//Set ITEMS ORDERED
textBlock2D[row, 3].Text = reportDataCollection[startIndex].GetItemsOrdered();
//Set AMOUNT DUE
textBlock2D[row, 4].Text = String.Format("{0:0.00}", Double.Parse(reportDataCollection[startIndex].GetAmountDue()));
//Set PAYMENT METHOD
textBlock2D[row, 5].Text = reportDataCollection[startIndex].GetPaymentMethod();
//Set NO (row number)
textBlock2D[row, 0].Text = (startIndex + 1).ToString();
startIndex++;
}
}
catch
{
//empty
}
}
}
示例13: ShedLoadByGroup
public void ShedLoadByGroup()
{
Curriculums.Clear();
Lessons.Clear();
HelpMessage = "Перетягивайте элементы на расписание";
if (SelectedGroup == null) return;
using (UniversitySheduleContainer cnt = new UniversitySheduleContainer("name=UniversitySheduleContainer"))
{
// узнаем форму обучения для группы
var group = (from g in cnt.Groups where g.Id == selectedGroup.Id select g).First();
int studytype = group.StudyTypeId;
//поставим начало срока обучения
if (group.EduPeriod.Count > 0) selecteddate = group.EduPeriod.First().Begin; // не обновится на форме..
// получим учебный план группы
IEnumerable<Curriculum> cur = (from lt in cnt.Curriculums.Include("RegulatoryAction").Include("RegulatoryAction.AcademicLoad").Include("RegulatoryAction.AcademicLoad.Employe") where lt.Group.Id == selectedGroup.Id select lt);
foreach (Curriculum c in cur)
{
var ra = c.RegulatoryAction;
var al = ra.AcademicLoad.First();
var e = al.Employe.Name;
var lt = ra.LessonsType.Name;
DisplayCurriculumLesson dispCurr = new DisplayCurriculumLesson()
{
_Subject = c.Subject.Name,
_Teacher = e,
_Type = lt,
_Regaction = ra.Id,
_Hours = ra.Hours,
// _Error = false,
};
Curriculums.Add(dispCurr);
}
// узнаем срок обучения группы чтобы не прокручивать расписание за его пределы
// .. откуда только?..
// ----------------------------------------
// в зависимости от формы обучения выводим расписание
// для заочников ищем по дате
// для очников по дню недели
int selectedWeekDayNumber = (int)selecteddate.DayOfWeek;
DateTime startDay = selecteddate.AddDays(1 - selectedWeekDayNumber); // начнём неделю с понедельника (а не с воскресенья)
DateTime endDay = startDay.AddDays(7);
if (studytype == 1) // очная
{
// заполняем табличку расписания для очников
for (int i = 1; i < 8; ++i) // lesson number
{
for (int j = 0; j < 7; ++j) // day
{
IEnumerable<Lesson> lessons = (from l in cnt.Lessons where l.RingId == i && l.Day == j && l.Period == upweek select l);
/// придумать вывод расписания от дня недели с определение типа недели (верх/низ)
/*j = (int)day.DayOfWeek - 1;
if (j < 0) j = 6;
days[j] = day.ToString("dddd d.MM.y");
OnPropertyChanged("Day" + (j + 1).ToString());*/
Collection<Lesson> filtered_lessons = new Collection<Lesson>();
foreach (var c in cur) // отбросим пары других групп
{
foreach (var l in lessons)
{
if (c.RegulatoryActionId == l.RegulatoryActionId)
filtered_lessons.Add(l);
}
}
DisplayCurriculumLesson dispLess = null;
if (filtered_lessons.Count() == 0)
{
dispLess = new DisplayCurriculumLesson();
}
else
{
var les = filtered_lessons.First();
var currsForLes = (from lt in cnt.Curriculums.Include("RegulatoryAction")
.Include("RegulatoryAction.AcademicLoad").Include("RegulatoryAction.AcademicLoad.Employe")
where lt.RegulatoryActionId == les.RegulatoryActionId
select lt);
var curForLes = currsForLes.First();
var ra = curForLes.RegulatoryAction;
var al = ra.AcademicLoad.First();
var e = al.Employe.Name;
var lesstype = ra.LessonsType.Name;
var auditorium = (from a in cnt.Auditoriums where a.Id == les.AuditoriumId select a).First();
bool flow = false;
if (currsForLes.Count() > 1) flow = true;
dispLess = new DisplayCurriculumLesson()
{
_Regaction = les.RegulatoryActionId,
_Subject = curForLes.Subject.Name,
_Teacher = e,
_Type = lesstype,
//_Error = false,
_LessonID = les.Id,
_Flow = flow,
_Auditorium = "ауд. " + auditorium.Number,
//.........这里部分代码省略.........
示例14: Prepare
/// <summary>
/// Prepare to next step
/// </summary>
/// <param name="neighborCells">Nearest neighbor <see cref="Cell"/> of organism - 24</param>
/// <returns><see cref="PrepareResult"/></returns>
public PrepareResult Prepare(Collection<Cell> neighborCells)
{
var result = new PrepareResult();
if (!_migrant)
{
var array = new Cell[5, 5];
var migrationMaybe = new Collection<Cell>();
var dictionary = new Dictionary<Cell, int>();
CreateArray5X5(neighborCells, array);
if (IsNeedMigration(array))
{
CreateDictionaryOfCountNeighbor(array, dictionary);
CreateAvaliableMigration(dictionary, migrationMaybe);
if (migrationMaybe.Count > 0)
{
var rand = new Random(Environment.TickCount + migrationMaybe.Count());
var migration = migrationMaybe[rand.Next(0, migrationMaybe.Count)];
var from = new Coordinate {X = _x, Y = _y};
var to = new Coordinate {X = migration.X, Y = migration.Y};
_x = to.X;
_y = to.Y;
_migrant = true;
result.SetMigration(from, to, this);
}
}
}
return result;
}
示例15: cmdgo_Click
private void cmdgo_Click(object sender, EventArgs e)
{
// maybe only random somekeys
Collection<Game> final = new Collection<Game>();
Collection<Game> initial = new Collection<Game>();
bool onlysteamlinked = (chkaddsteamlink.Enabled && chkaddsteamlink.Checked && chkignorenotbindedgame.Checked);
foreach (Game g in col2export) if ((onlysteamlinked && g.SteamId > 0) || !onlysteamlinked) initial.Add(g);
int maxrandomkey = Convert.ToInt32(txtrandomatmostkeys.Value);
if (chkrandommaxxkey.Checked && (col2export.Count > maxrandomkey))
{
Collection<Game> final2 = new Collection<Game>();
while (final2.Count < maxrandomkey)
{
Game nextgame = initial[new Random().Next(initial.Count())];
if (!final2.Contains(nextgame)) final2.Add(nextgame);
}
foreach (Game g in final2.OrderBy(g => g.Text).ToList()) final.Add(g);
}
else final = initial;
txtout.Text = txtintro.Text + Environment.NewLine;
foreach(Game g in final)
{
if ((chkignorenobal.Checked && g.KeysNotGiven > 0) || !chkignorenobal.Checked)
{
string newline = txtemotestart.Text;
string gamename = g.Text.Trim();
if (chkaddsteamlink.Enabled && chkaddsteamlink.Checked && g.SteamId > 0)
{
if (!chksteamincludedformat.Checked) gamename += " " + g.SteamApp.SteamAppUrl;
else gamename = string.Format("[URL={0}]{1}[/URL]", g.SteamApp.SteamAppUrl, gamename);
}
if (chkaddgamebalance.Checked)
{
string bal = g.KeysNotGiven.ToString();
if (chkavlformat1.Checked)
if (chkavlatstart.Checked) bal += " X ";
else bal = " X " + bal;
else if (chkavlformat2.Checked) bal = " [" + bal + "] ";
if (chkavlformat3.Checked)
{
if (chkrepeatcustom.Enabled && chkrepeatcustom.Checked)
{
bal = "";
for (int k = 0; k < g.KeysNotGiven; k++) bal += txtavlcustomformat.Text;
}
else bal = txtavlcustomformat.Text.Replace("%t", bal);
}
if (chkavlatstart.Checked) newline += bal;
newline += (gamename + txtaftergamename.Text);
if (chkavlatend.Checked) newline += bal;
}
else newline += gamename + txtaftergamename.Text;
txtout.Text += newline + txtemoteend.Text + Environment.NewLine; ;
}
}
txtout.Text += Environment.NewLine + txtend.Text;
if (chktimestamp.Checked) txtout.Text += Environment.NewLine + txttimestamp.Text.Replace("%t", DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString());
if (chkaddappinfo.Checked)
txtout.Text += Environment.NewLine + "[i]This list is cheerfully powered by " + App.Name + " v" + App.Version + ", created by AW[/i]";
if (chkreplaceclipboard.Checked) Functions.CliboardSafeTextSet(txtout.Text);
cmdcopy.Enabled = true;
}