Here are the examples of the csharp api System.Collections.Generic.List.Add(T) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2808 Examples
19
Source : DefaultRedisProvider.Set.cs
with MIT License
from AlphaYu
with MIT License
from AlphaYu
public List<T> SMembers<T>(string cacheKey)
{
ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey));
var list = new List<T>();
var bytes = _redisDb.SetMembers(cacheKey);
foreach (var item in bytes)
{
list.Add(_serializer.Deserialize<T>(item));
}
return list;
}
19
Source : DefaultRedisProvider.Set.cs
with MIT License
from AlphaYu
with MIT License
from AlphaYu
public List<T> SRandMember<T>(string cacheKey, int count = 1)
{
ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey));
var list = new List<T>();
var bytes = _redisDb.SetRandomMembers(cacheKey, count);
foreach (var item in bytes)
{
list.Add(_serializer.Deserialize<T>(item));
}
return list;
}
19
Source : DefaultRedisProvider.Set.cs
with MIT License
from AlphaYu
with MIT License
from AlphaYu
public async Task<List<T>> SMembersAsync<T>(string cacheKey)
{
ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey));
var list = new List<T>();
var vals = await _redisDb.SetMembersAsync(cacheKey);
foreach (var item in vals)
{
list.Add(_serializer.Deserialize<T>(item));
}
return list;
}
19
Source : DefaultRedisProvider.Set.cs
with MIT License
from AlphaYu
with MIT License
from AlphaYu
public async Task<List<T>> SRandMemberAsync<T>(string cacheKey, int count = 1)
{
ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey));
var list = new List<T>();
var bytes = await _redisDb.SetRandomMembersAsync(cacheKey, count);
foreach (var item in bytes)
{
list.Add(_serializer.Deserialize<T>(item));
}
return list;
}
19
Source : DefaultRedisProvider.SortedSet.cs
with MIT License
from AlphaYu
with MIT License
from AlphaYu
public List<T> ZRange<T>(string cacheKey, long start, long stop)
{
ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey));
var list = new List<T>();
var bytes = _redisDb.SortedSetRangeByRank(cacheKey, start, stop);
foreach (var item in bytes)
{
list.Add(_serializer.Deserialize<T>(item));
}
return list;
}
19
Source : DefaultRedisProvider.SortedSet.cs
with MIT License
from AlphaYu
with MIT License
from AlphaYu
public async Task<List<T>> ZRangeAsync<T>(string cacheKey, long start, long stop)
{
ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey));
var list = new List<T>();
var bytes = await _redisDb.SortedSetRangeByRankAsync(cacheKey, start, stop);
foreach (var item in bytes)
{
list.Add(_serializer.Deserialize<T>(item));
}
return list;
}
19
Source : Utils.cs
with MIT License
from Alprog
with MIT License
from Alprog
public static List<T> ToList<T>(this IEnumerable<T> ienumerable)
{
var list = new List<T>();
foreach (T item in ienumerable)
{
list.Add(item);
}
return list;
}
19
Source : ArrayHelper.cs
with MIT License
from AlternateLife
with MIT License
from AlternateLife
internal static List<T> ConvertFromIntPtr<T>(IntPtr arrayPointer, ulong size, Func<IntPtr, T> creator)
{
var elements = new List<T>();
var pointerSize = Marshal.SizeOf<IntPtr>();
for (var i = 0; i < (int) size; i++)
{
var targetPointer = Marshal.ReadIntPtr(arrayPointer + pointerSize * i);
elements.Add(creator(targetPointer));
}
return elements;
}
19
Source : RepositoryBase.cs
with MIT License
from ambleside138
with MIT License
from ambleside138
public void Add(T item)
{
_Collection.Add(item);
}
19
Source : Helper.cs
with MIT License
from amidos2006
with MIT License
from amidos2006
private static List<T> copyList<T>(List<T> list){
List<T> clone = new List<T>();
foreach(T v in list){
clone.Add(v);
}
return clone;
}
19
Source : FactoryExpression.cs
with MIT License
from amolines
with MIT License
from amolines
protected bool TryParseValues<T>(string key, TryParseHandler<T> handler, out T[] result)
where T : struct
{
result = null;
if (string.IsNullOrEmpty(key)) return false;
if (!TryGetValue(key, out var values)) return false;
var results = new List<T>();
foreach (var v in values)
{
if (handler(v, out var value))
results.Add(value);
}
if (!values.Length.Equals(results.Count)) return false;
result = results.ToArray();
return true;
}
19
Source : CachedEnumerable.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
internal bool GetNext(int index, out T value)
{
if (_disposer.IsDisposed)
{
value = null;
return false;
}
else if (index < _cache.Count)
{
value = _cache[index];
return true;
}
else if (index == _cache.Count)
{
if (!_atTheEnd)
{
if (_enumerator.MoveNext())
{
_cache.Add(value = _enumerator.Current);
return true;
}
else
{
_enumerator.Dispose();
_atTheEnd = true;
}
}
}
value = null;
return false;
}
19
Source : SyncArray.cs
with MIT License
from anderm
with MIT License
from anderm
public T[] GetDataArray()
{
var childrenList = new List<T>(dataArray.Count);
foreach (KeyValuePair<string, T> pair in dataArray)
{
childrenList.Add(pair.Value);
}
return childrenList.ToArray();
}
19
Source : TrackableManager.cs
with Apache License 2.0
from andijakl
with Apache License 2.0
from andijakl
private void _SafeAdd<T>(Trackable trackable, List<T> trackables) where T : Trackable
{
if (trackable is T)
{
trackables.Add(trackable as T);
}
}
19
Source : MarshalingHelper.cs
with Apache License 2.0
from andijakl
with Apache License 2.0
from andijakl
public static void AddUnmanagedStructArrayToList<T>(IntPtr arrayPtr, int arrayLength, List<T> list) where T : struct
{
if (arrayPtr == IntPtr.Zero || list == null)
{
return;
}
for (int i = 0; i < arrayLength; i++)
{
list.Add((T)Marshal.PtrToStructure(GetPtrToUnmanagedArrayElement<T>(arrayPtr, i), typeof(T)));
}
}
19
Source : Notifiable.cs
with MIT License
from andrebaltieri
with MIT License
from andrebaltieri
public void AddNotification(string key, string message)
{
var notification = GetNotificationInstance(key, message);
_notifications.Add(notification);
}
19
Source : Notifiable.cs
with MIT License
from andrebaltieri
with MIT License
from andrebaltieri
public void AddNotification(T notification)
{
_notifications.Add(notification);
}
19
Source : Notifiable.cs
with MIT License
from andrebaltieri
with MIT License
from andrebaltieri
public void AddNotification(Type property, string message)
{
var notification = GetNotificationInstance(property?.Name, message);
_notifications.Add(notification);
}
19
Source : FrameworkElementExtensions.cs
with GNU General Public License v3.0
from AndreiFedarets
with GNU General Public License v3.0
from AndreiFedarets
public static IList<T> FindChildrenRecursive<T>(this UIElement element) where T : clreplaced
{
List<T> children = new List<T>();
if (element is T)
{
children.Add(element as T);
}
Panel panel = element as Panel;
if (panel != null)
{
foreach (UIElement panelItem in panel.Children)
{
IList<T> subchildren = panelItem.FindChildrenRecursive<T>();
children.AddRange(subchildren);
}
}
ContentControl contentControl = element as ContentControl;
if (contentControl != null)
{
UIElement visual = contentControl.Content as UIElement;
if (visual != null)
{
IList<T> subchildren = visual.FindChildrenRecursive<T>();
children.AddRange(subchildren);
}
}
return children;
}
19
Source : DependencyObjectExtensions.cs
with GNU General Public License v3.0
from AndreiFedarets
with GNU General Public License v3.0
from AndreiFedarets
public static void FindVisualChildren<T>(this DependencyObject dependencyObject, List<T> results) where T : DependencyObject
{
int count = VisualTreeHelper.GetChildrenCount(dependencyObject);
for (int i = 0; i < count; i++)
{
DependencyObject currentObject = VisualTreeHelper.GetChild(dependencyObject, i);
T current = currentObject as T;
if (current != null)
{
results.Add(current);
}
FindVisualChildren<T>(currentObject, results);
}
}
19
Source : DataTable.cs
with GNU General Public License v3.0
from AndreiFedarets
with GNU General Public License v3.0
from AndreiFedarets
private List<T> LoadItems(string query)
{
lock (_lock)
{
List<T> items = new List<T>();
SQLiteCommand command = _connection.CreateCommand();
command.CommandText = query;
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
{
T item = ParseItem(reader);
items.Add(item);
}
return items;
}
}
19
Source : UnitCollectionBase.cs
with GNU General Public License v3.0
from AndreiFedarets
with GNU General Public License v3.0
from AndreiFedarets
private void UpdateUnits(IEnumerable<T> units)
{
List<T> updatedUnits = new List<T>();
lock (_lock)
{
foreach (T unit in units)
{
bool newUnit = false;
T proxyUnit;
if (_dictionaryByUid.TryGetValue(unit.Uid, out proxyUnit))
{
proxyUnit.Update(unit.NativeUnit);
}
else
{
proxyUnit = Convert(unit);
_dictionaryByUid.Add(unit.Uid, proxyUnit);
newUnit = true;
}
updatedUnits.Add(proxyUnit);
List<T> theSameIdUnits;
if (!_dictionaryById.TryGetValue(proxyUnit.Id, out theSameIdUnits))
{
theSameIdUnits = new List<T>();
_dictionaryById.Add(proxyUnit.Id, theSameIdUnits);
}
theSameIdUnits.Add(proxyUnit);
if (newUnit)
{
_collection.Add(proxyUnit);
}
}
}
_unitsUpdatedEvent.Raise(this, () => new UnitCollectionEventArgs<T>(updatedUnits.ToArray()));
}
19
Source : DaemonUnitCollection.cs
with GNU General Public License v3.0
from AndreiFedarets
with GNU General Public License v3.0
from AndreiFedarets
private void UpdateUnitInternal(T unit)
{
_dictionaryByUid[unit.Uid] = unit;
List<T> theSameIdUnits;
if (!_dictionaryById.TryGetValue(unit.Id, out theSameIdUnits))
{
theSameIdUnits = new List<T>();
_dictionaryById.Add(unit.Id, theSameIdUnits);
}
theSameIdUnits.Add(unit);
}
19
Source : ConcurentList.cs
with GNU General Public License v3.0
from AndreiFedarets
with GNU General Public License v3.0
from AndreiFedarets
public void Add(T item)
{
lock (_items)
{
_items.Add(item);
}
}
19
Source : SqlMapper.Async.cs
with MIT License
from anet-team
with MIT License
from anet-team
internal static async Task<IEnumerable<T>> QueryAsync<T>(this IDbConnection cnn, Type effectiveType, CommandDefinition command)
{
object param = command.Parameters;
var idenreplacedy = new Idenreplacedy(command.CommandText, command.CommandType, cnn, effectiveType, param?.GetType(), null);
var info = GetCacheInfo(idenreplacedy, param, command.AddToCache);
bool wasClosed = cnn.State == ConnectionState.Closed;
var cancel = command.CancellationToken;
using (var cmd = command.TrySetupAsyncCommand(cnn, info.ParamReader))
{
DbDataReader reader = null;
try
{
if (wasClosed) await cnn.TryOpenAsync(cancel).ConfigureAwait(false);
reader = await ExecuteReaderWithFlagsFallbackAsync(cmd, wasClosed, CommandBehavior.SequentialAccess | CommandBehavior.SingleResult, cancel).ConfigureAwait(false);
var tuple = info.Deserializer;
int hash = GetColumnHash(reader);
if (tuple.Func == null || tuple.Hash != hash)
{
if (reader.FieldCount == 0)
return Enumerable.Empty<T>();
tuple = info.Deserializer = new DeserializerState(hash, GetDeserializer(effectiveType, reader, 0, -1, false));
if (command.AddToCache) SetQueryCache(idenreplacedy, info);
}
var func = tuple.Func;
if (command.Buffered)
{
var buffer = new List<T>();
var convertToType = Nullable.GetUnderlyingType(effectiveType) ?? effectiveType;
while (await reader.ReadAsync(cancel).ConfigureAwait(false))
{
object val = func(reader);
if (val == null || val is T)
{
buffer.Add((T)val);
}
else
{
buffer.Add((T)Convert.ChangeType(val, convertToType, CultureInfo.InvariantCulture));
}
}
while (await reader.NextResultAsync(cancel).ConfigureAwait(false)) { /* ignore subsequent result sets */ }
command.OnCompleted();
return buffer;
}
else
{
// can't use ReadAsync / cancellation; but this will have to do
wasClosed = false; // don't close if handing back an open reader; rely on the command-behavior
var deferred = ExecuteReaderSync<T>(reader, func, command.Parameters);
reader = null; // to prevent it being disposed before the caller gets to see it
return deferred;
}
}
finally
{
using (reader) { /* dispose if non-null */ }
if (wasClosed) cnn.Close();
}
}
}
19
Source : SqlMapper.GridReader.Async.cs
with MIT License
from anet-team
with MIT License
from anet-team
private async Task<IEnumerable<T>> ReadBufferedAsync<T>(int index, Func<IDataReader, object> deserializer)
{
try
{
var reader = (DbDataReader)this.reader;
var buffer = new List<T>();
while (index == gridIndex && await reader.ReadAsync(cancel).ConfigureAwait(false))
{
buffer.Add((T)deserializer(reader));
}
return buffer;
}
finally // finally so that First etc progresses things even when multiple rows
{
if (index == gridIndex)
{
await NextResultAsync().ConfigureAwait(false);
}
}
}
19
Source : DnaConfiguration.cs
with MIT License
from angelsix
with MIT License
from angelsix
private static void TryGetSettingList<T>(Expression<Func<List<T>>> currentValueExpression, Expression<Func<List<T>>> finalValueExpression, bool resolvePath = false, string currentPath = null, Func<T, string> logDetails = null)
where T : clreplaced
{
// Get the current value
var currentList = currentValueExpression.GetPropertyValue();
// Get property name (for the logs)
var propertyName = currentValueExpression.GetPropertyName();
// NOTE: We merge lists we don't replace them
// Get existing list
var existingList = finalValueExpression.GetPropertyValue() as List<T>;
// If it's null, create it
if (existingList == null)
existingList = new List<T>();
// Add current values
if (currentList?.Count > 0)
{
currentList.ForEach(currenreplacedem =>
{
// Resolve if this is a string
if (currenreplacedem is string)
currenreplacedem = ResolveFullPath(currentPath, currenreplacedem as string, true, out bool wasRelative) as T;
// Add to list
existingList.Add(currenreplacedem);
// Log it
// Use LogDetails callback if provided
// If not check if item is a string
// Failing that just log "New Item"
var detail = logDetails != null ? logDetails(currenreplacedem) : (currenreplacedem is string ? currenreplacedem as string : "New Item");
CoreLogger.LogTabbed(propertyName, detail, 1);
});
// Set final setting
//
// NOTE: If list is of clreplacedes, and the clreplaced implements IEquatible<T>
// then this distinct will work for filtering out duplicates
//
// Native values like string lists should automatically match
// with hash codes and work
//
finalValueExpression.SetPropertyValue<List<T>>(existingList.Distinct().ToList());
}
}
19
Source : PriorityQueue.cs
with Apache License 2.0
from AnkiUniversal
with Apache License 2.0
from AnkiUniversal
public void Add(T item)
{
data.Add(item);
int childIndex = data.Count - 1;
while (childIndex > 0)
{
int parentIndex = (childIndex - 1) / 2;
if (data[childIndex].CompareTo(data[parentIndex]) >= 0)
break;
SwapParentAndChild(parentIndex, childIndex);
childIndex = parentIndex;
}
}
19
Source : TokenizerBase.cs
with Apache License 2.0
from AnkiUniversal
with Apache License 2.0
from AnkiUniversal
private List<T> CreateTokenList(int offset, string text)
{
List<T> result = new List<T>();
ViterbiLattice lattice = viterbiBuilder.Build(text);
List<ViterbiNode> bestPath = viterbiSearcher.Search(lattice);
foreach (ViterbiNode node in bestPath)
{
int wordId = node.WordId;
if (node.Type == ViterbiNode.NodeType.KNOWN && wordId == -1)
{ // Do not include BOS/EOS
continue;
}
T token = (T)tokenFactory.CreateToken(
wordId,
node.Surface,
node.Type,
offset + node.StartIndex,
dictionaryMap[node.Type]
);
result.Add(token);
}
return result;
}
19
Source : WorkspaceItemCollection.cs
with Apache License 2.0
from anmcgrath
with Apache License 2.0
from anmcgrath
public void Add(T item, string key)
{
//this[key] = item;
listCollection.Add(item);
}
19
Source : WorkspaceItemCollection.cs
with Apache License 2.0
from anmcgrath
with Apache License 2.0
from anmcgrath
public void Add(T item)
{
listCollection.Add(item);
}
19
Source : QuadTree.cs
with MIT License
from AnnoDesigner
with MIT License
from AnnoDesigner
public void Add(T item, Rect bounds)
{
if (!LastLevelQuadrant)
{
if (topRightBounds.Contains(bounds))
{
TopRight ??= new Quadrant(topRightBounds);
TopRight.Add(item, bounds);
}
else if (topLeftBounds.Contains(bounds))
{
TopLeft ??= new Quadrant(topLeftBounds);
TopLeft.Add(item, bounds);
}
else if (bottomRightBounds.Contains(bounds))
{
BottomRight ??= new Quadrant(bottomRightBounds);
BottomRight.Add(item, bounds);
}
else if (bottomLeftBounds.Contains(bounds))
{
BottomLeft ??= new Quadrant(bottomLeftBounds);
BottomLeft.Add(item, bounds);
}
else
{
ItemsInQuadrant.Add(item);
}
}
else
{
ItemsInQuadrant.Add(item);
}
}
19
Source : BinaryHeap.cs
with GNU General Public License v3.0
from anotak
with GNU General Public License v3.0
from anotak
public virtual void Add(T item)
{
int index = heap.Count;
// Add to the end of the heap
heap.Add(item);
// Continue until the item is at the top
// or compares higher to the parent item
while((index > 0) && (heap[index].CompareTo(heap[ParentOf(index)]) > 0))
{
// Swap with parent item
SwapItems(index, ParentOf(index));
index = ParentOf(index);
}
}
19
Source : QueueDictionary.cs
with MIT License
from AnotherEnd15
with MIT License
from AnotherEnd15
public void Enqueue(T t, K k)
{
this.list.Add(t);
this.dictionary.Add(t, k);
}
19
Source : RandomHelper.cs
with MIT License
from AnotherEnd15
with MIT License
from AnotherEnd15
public static bool GetRandListByCount<T>(List<T> sourceList, List<T> destList, int randCount)
{
if (sourceList == null || destList == null || randCount < 0)
{
return false;
}
destList.Clear();
if (randCount >= sourceList.Count)
{
foreach (var val in sourceList)
{
destList.Add(val);
}
return true;
}
if (randCount == 0)
{
return true;
}
int beginIndex = random.Next(0, sourceList.Count - 1);
for (int i = beginIndex; i < beginIndex + randCount; i++)
{
destList.Add(sourceList[i % sourceList.Count]);
}
return true;
}
19
Source : LeanClassPool.cs
with Apache License 2.0
from AnotherEnd15
with Apache License 2.0
from AnotherEnd15
public static void Despawn(T instance, System.Action<T> onDespawn)
{
// Does it exist?
if (instance != null)
{
// Run action on it?
if (onDespawn != null)
{
onDespawn(instance);
}
// Add to cache
cache.Add(instance);
}
}
19
Source : ObjectPool.cs
with Apache License 2.0
from anpShawn
with Apache License 2.0
from anpShawn
public T GetNext()
{
for(int i=0; i<pool.Length; i++)
{
if(!pool[i].IsActiveInPool())
{
pool[i].ActivateForPool();
return pool[i];
}
}
//can we make an overflow object if no others are available?
if(overflowIsAllowed)
{
T overflowObj = FuncCreatePoolObject(poolTypeName + "_overflow_" + overflow.Count);
overflowObj.InitForPool();
overflowObj.ActivateForPool();
overflow.Add(overflowObj);
return overflowObj;
}
else
throw new Exception("Pool has no inactive members to distribute");
}
19
Source : TopologicalSort.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
public static void Visit<T>(T item, Func<T, IEnumerable<T>> getDependencies, List<T> sorted, Dictionary<T, bool> visited, bool ignoreCycles)
{
bool inProcess;
var alreadyVisited = visited.TryGetValue(item, out inProcess);
if (alreadyVisited)
{
if (inProcess && !ignoreCycles)
{
throw new ArgumentException("Cyclic dependency found.");
}
}
else
{
visited[item] = true;
var dependencies = getDependencies(item);
if (dependencies != null)
{
foreach (var dependency in dependencies)
{
Visit(dependency, getDependencies, sorted, visited, ignoreCycles);
}
}
visited[item] = false;
sorted.Add(item);
}
}
19
Source : IObjectRepository.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
public async Task<List<T>> ToListAsync()
{
var list = new List<T>();
await foreach(var item in this)
{
list.Add(item);
}
return list;
}
19
Source : NamedItemCollection.cs
with MIT License
from ansel86castro
with MIT License
from ansel86castro
public void Add(T item)
{
_lookup[item.Name] = _items.Count;
_items.Add(item);
HookNameChanged(item);
}
19
Source : Dbg.cs
with Apache License 2.0
from AnthonyLloyd
with Apache License 2.0
from AnthonyLloyd
public IEnumerator<T> GetEnumerator()
{
int index = 0;
for (; index < _cache.Count; index++) yield return _cache[index];
for (; _enumerator != null && _enumerator.MoveNext(); index++)
{
var current = _enumerator.Current;
_cache.Add(current);
yield return current;
}
if (_enumerator != null)
{
_enumerator.Dispose();
_enumerator = null;
}
for (; index < _cache.Count; index++) yield return _cache[index];
}
19
Source : ResourceManager.cs
with MIT License
from antonsem
with MIT License
from antonsem
public T Get(Vector3 position, Vector3 rotation, Transform parent)
{
for (int i = 0; i < componentPool.Count; i++)
{
if (componentPool[i].gameObject.activeInHierarchy)
continue;
componentPool[i].transform.SetParent(parent);
componentPool[i].transform.position = position;
componentPool[i].transform.rotation = Quaternion.Euler(rotation);
componentPool[i].gameObject.SetActive(true);
return componentPool[i];
}
GameObject obj = Instantiate(prefab, position, Quaternion.Euler(rotation));
if (!obj.transform.TryGetComponent(out T component))
{
Debug.LogError($"Prefab {prefab.name} doesn't have a component of type {typeof(T)}!");
return null;
}
componentPool.Add(component);
componentPool[componentPool.Count - 1].transform.SetParent(parent);
return componentPool[componentPool.Count - 1];
}
19
Source : ResourceManager.cs
with MIT License
from antonsem
with MIT License
from antonsem
public void Prepare(int count = 1)
{
for (int i = 0; i < count; i++)
{
GameObject
obj = Instantiate(prefab, Pool); //Instantiate under the Pool so the Awake() is not invoked
if (!obj.transform.TryGetComponent(out T component))
{
Debug.LogError($"Prefab {prefab.name} doesn't have a component of type {typeof(T)}!");
continue;
}
componentPool.Add(component);
componentPool[componentPool.Count - 1].gameObject.SetActive(false);
}
}
19
Source : MDTable.cs
with GNU General Public License v3.0
from anydream
with GNU General Public License v3.0
from anydream
public uint Create(T row) {
if (isReadOnly)
throw new ModuleWriterException(string.Format("Trying to modify table {0} after it's been set to read-only", table));
uint rid = (uint)cached.Count + 1;
if (!cachedDict.ContainsKey(row))
cachedDict[row] = rid;
cached.Add(row);
return rid;
}
19
Source : Helper.cs
with GNU General Public License v3.0
from anydream
with GNU General Public License v3.0
from anydream
public static List<T> SortStable<T>(this List<T> ary, Comparison<T> comp)
{
List<int> idxAry = new List<int>();
for (int i = 0; i < ary.Count; ++i)
idxAry.Add(i);
idxAry.Sort((ilhs, irhs) =>
{
int res = comp(ary[ilhs], ary[irhs]);
if (res == 0)
return ilhs.CompareTo(irhs);
return res;
});
List<T> result = new List<T>();
foreach (int idx in idxAry)
result.Add(ary[idx]);
return result;
}
19
Source : DatabaseOperation.cs
with MIT License
from ap0405140
with MIT License
from ap0405140
public List<T> Query<T>(string sTsql, bool closeconnect = true)
{
DataTable dt;
List<T> ls;
T tt;
object tt2;
PropertyInfo[] props;
FieldInfo fieldinfo;
DataColumn[] dtcolumns;
ColumnAttribute[] columnattributes;
string targettype, columnname;
int i;
try
{
dt = Query(sTsql, closeconnect);
dtcolumns = dt.Columns.Cast<DataColumn>().ToArray();
ls = new List<T>();
targettype = "";
if (typeof(T).IsValueType
|| typeof(T).Name.ToLower().Contains("string"))
{
targettype = "ValueType";
}
if (typeof(T).Name.StartsWith("ValueTuple"))
{
targettype = "ValueTuple";
}
if (typeof(T).GetConstructors().Any(p => p.GetParameters().Length == 0))
{
targettype = "Clreplaced";
}
foreach (DataRow dr in dt.Rows)
{
switch (targettype)
{
case "ValueType":
tt = (dr[0] == DBNull.Value ? default(T) : (T)dr[0]);
ls.Add(tt);
break;
case "ValueTuple":
tt = Activator.CreateInstance<T>();
tt2 = tt;
for (i = 0; i <= dtcolumns.Length - 1; i++)
{
fieldinfo = tt2.GetType().GetField("Item" + (i + 1).ToString());
if (fieldinfo != null)
{
fieldinfo.SetValue(tt2, (dr[i] == DBNull.Value ? null : dr[i].ToSpecifiedType(fieldinfo.FieldType)));
}
}
tt = (T)tt2;
ls.Add(tt);
break;
case "Clreplaced":
tt = (T)Activator.CreateInstance(typeof(T));
props = typeof(T).GetProperties();
foreach (PropertyInfo prop in props)
{
columnattributes = prop.GetCustomAttributes(typeof(ColumnAttribute), false).Cast<ColumnAttribute>().ToArray();
columnname = (columnattributes.Length > 0 && string.IsNullOrEmpty(columnattributes[0].Name) == false
?
columnattributes[0].Name
:
prop.Name);
if (dtcolumns.Any(c => c.ColumnName == columnname))
{
prop.SetValue(tt, (dr[columnname] == DBNull.Value ? null : dr[columnname]));
}
}
ls.Add(tt);
break;
default:
break;
}
}
return ls;
}
catch (Exception ex)
{
throw new Exception("Run SQL: \r\n" + sTsql
+ "\r\n\r\n" + "ExceptionSource: " + ex.Source
+ "\r\n\r\n" + "ExceptionMessage: " + ex.Message);
}
finally
{
//if (closeconnect == true)
//{
// if (scn.State == ConnectionState.Open)
// {
// scn.Close();
// }
// scn.Dispose();
//}
}
}
19
Source : FindRelatedClasses.cs
with MIT License
from apexsharp
with MIT License
from apexsharp
public static void AddItem<T>(this List<T> list, T item)
{
if (!list.Contains(item))
{
list.Add(item);
}
}
19
Source : ListImplementation.cs
with MIT License
from apexsharp
with MIT License
from apexsharp
public void add(T item) => list.Add(item);
19
Source : PathConstructor.cs
with MIT License
from ApmeM
with MIT License
from ApmeM
public static List<T> RecontructPath<T>(Dictionary<T, T> cameFrom, T start, T goal)
{
var path = new List<T>();
var current = goal;
path.Add(goal);
while (!current.Equals(start))
{
current = cameFrom[current];
path.Add(current);
}
path.Reverse();
return path;
}
19
Source : ExcelPivotTableFieldCollection.cs
with Apache License 2.0
from Appdynamics
with Apache License 2.0
from Appdynamics
internal void AddInternal(T field)
{
_list.Add(field);
}
See More Examples