System.Collections.Generic.IEnumerable.Sum(System.Func)

Here are the examples of the csharp api System.Collections.Generic.IEnumerable.Sum(System.Func) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1989 Examples 7

19 Source : ParamSfo.cs
with MIT License
from 13xforever

public void WriteTo(Stream stream)
        {
            if (!stream.CanSeek)
                throw new ArgumentException("Stream must be seekable", nameof(stream));

            var utf8 = new UTF8Encoding(false);
            using var writer = new BinaryWriter(stream, utf8, true);
            writer.Write(utf8.GetBytes(Magic));
            writer.Write(MajorVersion);
            writer.Write(MinorVersion);
            writer.Write(Reserved1);
            KeysOffset = 0x14 + Items.Count * 0x10;
            writer.Write(KeysOffset);
            ValuesOffset = KeysOffset + Items.Sum(i => i.Key.Length + 1);
            if (ValuesOffset % 4 != 0)
                ValuesOffset = (ValuesOffset / 4 + 1) * 4;
            writer.Write(ValuesOffset);
            ItemCount = Items.Count;
            writer.Write(ItemCount);

            int lastKeyOffset = KeysOffset;
            int lastValueOffset = ValuesOffset;
            for (var i = 0; i < Items.Count; i++)
            {
                var entry = Items[i];

                writer.BaseStream.Seek(0x14 + i * 0x10, SeekOrigin.Begin);
                writer.Write((ushort)(lastKeyOffset - KeysOffset));
                writer.Write((ushort)entry.ValueFormat);
                writer.Write(entry.ValueLength);
                writer.Write(entry.ValueMaxLength);
                writer.Write(lastValueOffset - ValuesOffset);

                writer.BaseStream.Seek(lastKeyOffset, SeekOrigin.Begin);
                writer.Write(utf8.GetBytes(entry.Key));
                writer.Write((byte)0);
                lastKeyOffset = (int)writer.BaseStream.Position;

                writer.BaseStream.Seek(lastValueOffset, SeekOrigin.Begin);
                writer.Write(entry.BinaryValue);
                lastValueOffset = (int)writer.BaseStream.Position;
            }
        }

19 Source : Dumper.cs
with MIT License
from 13xforever

public async Task DumpAsync(string output)
        {
            // check and create output folder
            var dumpPath = output;
            while (!string.IsNullOrEmpty(dumpPath) && !Directory.Exists(dumpPath))
            {
                var parent = Path.GetDirectoryName(dumpPath);
                if (parent == null || parent == dumpPath)
                    dumpPath = null;
                else
                    dumpPath = parent;
            }
            if (filesystemStructure is null)
                (filesystemStructure, emptyDirStructure) = GetFilesystemStructure();
            var validators = GetValidationInfo();
            if (!string.IsNullOrEmpty(dumpPath))
            {
                var root = Path.GetPathRoot(Path.GetFullPath(output));
                var drive = DriveInfo.GetDrives().FirstOrDefault(d => d?.RootDirectory.FullName.StartsWith(root) ?? false);
                if (drive != null)
                {
                    var spaceAvailable = drive.AvailableFreeSpace;
                    TotalFileSize = filesystemStructure.Sum(f => f.Length);
                    var diff = TotalFileSize + 100 * 1024 - spaceAvailable;
                    if (diff > 0)
                        Log.Warn($"Target drive might require {diff.replacedtorageUnit()} of additional free space");
                }
            }

            foreach (var dir in emptyDirStructure)
                Log.Trace($"Empty dir: {dir}");
            foreach (var file in filesystemStructure)
                Log.Trace($"0x{file.StartSector:x8}: {file.Filename} ({file.Length})");
            var outputPathBase = Path.Combine(output, OutputDir);
            if (!Directory.Exists(outputPathBase))
                Directory.CreateDirectory(outputPathBase);

            TotalFileCount = filesystemStructure.Count;
            TotalSectors = discReader.TotalClusters;
            Log.Debug("Using decryption key: " + allMatchingKeys.First().DecryptedKeyId);
            var decryptionKey = allMatchingKeys.First().DecryptedKey;
            var sectorSize = (int)discReader.ClusterSize;
            var unprotectedRegions = driveStream.GetUnprotectedRegions();
            ValidationStatus = true;

            foreach (var dir in emptyDirStructure)
            {
                try
                {
                    if (Cts.IsCancellationRequested)
                        return;

                    var convertedName = Path.DirectorySeparatorChar == '\\' ? dir : dir.Replace('\\', Path.DirectorySeparatorChar);
                    var outputName = Path.Combine(outputPathBase, convertedName);
                    if (!Directory.Exists(outputName))
                    {
                        Log.Debug("Creating empty directory " + outputName);
                        Directory.CreateDirectory(outputName);
                    }
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                    BrokenFiles.Add((dir, "Unexpected error: " + ex.Message));
                }
            }
            
            foreach (var file in filesystemStructure)
            {
                try
                {
                    if (Cts.IsCancellationRequested)
                        return;

                    Log.Info($"Reading {file.Filename} ({file.Length.replacedtorageUnit()})");
                    CurrentFileNumber++;
                    var convertedFilename = Path.DirectorySeparatorChar == '\\' ? file.Filename : file.Filename.Replace('\\', Path.DirectorySeparatorChar);
                    var inputFilename = Path.Combine(input, convertedFilename);

                    if (!File.Exists(inputFilename))
                    {
                        Log.Error($"Missing {file.Filename}");
                        BrokenFiles.Add((file.Filename, "missing"));
                        continue;
                    }

                    var outputFilename = Path.Combine(outputPathBase, convertedFilename);
                    var fileDir = Path.GetDirectoryName(outputFilename);
                    if (!Directory.Exists(fileDir))
                    {
                        Log.Debug("Creating directory " + fileDir);
                        Directory.CreateDirectory(fileDir);
                    }

                    var error = false;
                    var expectedHashes = (
                        from v in validators
                        where v.Files.ContainsKey(file.Filename)
                        select v.Files[file.Filename].Hashes
                    ).ToList();
                    var lastHash = "";
                    var tries = 2;
                    do
                    {
                        try
                        {
                            tries--;
                            using var outputStream = File.Open(outputFilename, FileMode.Create, FileAccess.Write, FileShare.Read);
                            using var inputStream = File.Open(inputFilename, FileMode.Open, FileAccess.Read, FileShare.Read);
                            using var decrypter = new Decrypter(inputStream, driveStream, decryptionKey, file.StartSector, sectorSize, unprotectedRegions);
                            Decrypter = decrypter;
                            await decrypter.CopyToAsync(outputStream, 8 * 1024 * 1024, Cts.Token).ConfigureAwait(false);
                            outputStream.Flush();
                            var resultHashes = decrypter.GetHashes();
                            var resultMd5 = resultHashes["MD5"];
                            if (decrypter.WasEncrypted && decrypter.WasUnprotected)
                                Log.Debug("Partially decrypted " + file.Filename);
                            else if (decrypter.WasEncrypted)
                                Log.Debug("Decrypted " + file.Filename);

                            if (!expectedHashes.Any())
                            {
                                if (ValidationStatus == true)
                                    ValidationStatus = null;
                            }
                            else if (!IsMatch(resultHashes, expectedHashes))
                            {
                                error = true;
                                var msg = "Unexpected hash: " + resultMd5;
                                if (resultMd5 == lastHash || decrypter.LastBlockCorrupted)
                                {
                                    Log.Error(msg);
                                    BrokenFiles.Add((file.Filename, "corrupted"));
                                    break;
                                }
                                Log.Warn(msg + ", retrying");
                            }

                            lastHash = resultMd5;
                        }
                        catch (Exception e)
                        {
                            Log.Error(e, e.Message);
                            error = true;
                        }
                    } while (error && tries > 0 && !Cts.IsCancellationRequested);
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                    BrokenFiles.Add((file.Filename, "Unexpected error: " + ex.Message));
                }
            }
            Log.Info("Completed");
        }

19 Source : PkgChecker.cs
with MIT License
from 13xforever

internal static async Task CheckAsync(List<FileInfo> pkgList, int fnameWidth, int sigWidth, int csumWidth, int allCsumsWidth, CancellationToken cancellationToken)
        {
            TotalFileSize = pkgList.Sum(i => i.Length);

            var buf = new byte[1024 * 1024]; // 1 MB
            foreach (var item in pkgList)
            {
                Write($"{item.Name.Trim(fnameWidth).PadRight(fnameWidth)} ");
                try
                {
                    CurrentPadding = sigWidth;
                    CurrentFileSize = item.Length;
                    if (item.Length < 0xC0 + 0x20) // header + csum at the end
                    {
                        Write("invalid pkg".PadLeft(allCsumsWidth) + Environment.NewLine, ConsoleColor.Red);
                        continue;
                    }

                    using var file = File.Open(item.FullName, FileMode.Open, FileAccess.Read, FileShare.Read);
                    var header = new byte[0xc0];
                    file.ReadExact(header);
                    byte[] sha1Sum = null;
                    using (var sha1 = SHA1.Create())
                        sha1Sum = sha1.ComputeHash(header, 0, 0x80);
                    if (!ValidateCmac(header))
                        Write("cmac".PadLeft(sigWidth) + " ", ConsoleColor.Red);
                    else if (!ValidateHash(header, sha1Sum))
                        Write("sha1".PadLeft(sigWidth) + " ", ConsoleColor.Yellow);
                    else if (!ValidateSigNew(header, sha1Sum))
                    {
                        if (!ValidateSigOld(header, sha1Sum))
                            Write("ecdsa".PadLeft(sigWidth) + " ", ConsoleColor.Red);
                        else
                            Write("ok (old)".PadLeft(sigWidth) + " ", ConsoleColor.Yellow);
                    }
                    else
                        Write("ok".PadLeft(sigWidth) + " ", ConsoleColor.Green);

                    CurrentPadding = csumWidth;
                    file.Seek(0, SeekOrigin.Begin);
                    byte[] hash;
                    using (var sha1 = SHA1.Create())
                    {
                        var dataLengthToHash = CurrentFileSize - 0x20;
                        int read;
                        do
                        {
                            read = await file.ReadAsync(buf, 0, (int)Math.Min(buf.Length, dataLengthToHash - CurrentFileProcessedBytes), cancellationToken).ConfigureAwait(false);
                            CurrentFileProcessedBytes += read;
                            sha1.TransformBlock(buf, 0, read, null, 0);
                        } while (read > 0 && CurrentFileProcessedBytes < dataLengthToHash && !cancellationToken.IsCancellationRequested);
                        sha1.TransformFinalBlock(buf, 0, 0);
                        hash = sha1.Hash;
                    }
                    if (cancellationToken.IsCancellationRequested)
                        return;

                    var expectedHash = new byte[0x14];
                    file.ReadExact(expectedHash);
                    CurrentFileProcessedBytes += 0x20;
                    if (!expectedHash.SequenceEqual(hash))
                        Write("fail".PadLeft(csumWidth) + Environment.NewLine, ConsoleColor.Red);
                    else
                        Write("ok".PadLeft(csumWidth) + Environment.NewLine, ConsoleColor.Green);
                }
                catch (Exception e)
                {
                    Write("Error" + Environment.NewLine + e.Message + Environment.NewLine, ConsoleColor.Red);
                }
                finally
                {
                    ProcessedBytes += CurrentFileSize;
                    CurrentFileProcessedBytes = 0;
                    CurrentPadding = 0;
                }
                if (cancellationToken.IsCancellationRequested)
                    return;
            }
        }

19 Source : AdjacentSeats.cs
with Apache License 2.0
from 42skillz

public int ComputeDistanceFromRowCentroid(int rowSize)
        {
            return _seats.Select(s => s.DistanceFromRowCentroid).ToList().Sum() / _seats.Count;
        }

19 Source : AggregateMessage.cs
with MIT License
from a1q123456

public override void Serialize(SerializationContext context)
        {
            int bytesNeed = (int)(Messages.Count * 11 + Messages.Sum(m => m.DataLength));
            var buffer = _arrayPool.Rent(bytesNeed);
            try
            {
                var span = buffer.replacedpan(0, bytesNeed);
                int consumed = 0;
                foreach (var message in Messages)
                {
                    span[0] = (byte)message.Header.MessageType;
                    span = span.Slice(sizeof(byte));
                    NetworkBitConverter.TryGetUInt24Bytes((uint)message.Header.MessageLength, span);
                    span = span.Slice(3);
                    NetworkBitConverter.TryGetBytes(message.Header.Timestamp, span);
                    span = span.Slice(4);
                    NetworkBitConverter.TryGetUInt24Bytes((uint)MessageHeader.MessageStreamId, span);
                    span = span.Slice(3);
                    MessageBuffer.replacedpan(consumed, (int)message.Header.MessageLength).CopyTo(span);
                    consumed += (int)message.Header.MessageLength;
                    span = span.Slice((int)message.Header.MessageLength);
                }
                context.WriteBuffer.WriteToBuffer(span);
            }
            finally
            {
                _arrayPool.Return(buffer);
            }
        }

19 Source : WorkbookStream.cs
with Apache License 2.0
from aaaddress1

public long GetRecordByteOffset(BiffRecord record)
        {
            int listOffset = GetRecordOffset(record);
            //Size of BiffRecord is 4 (header) + Length
            return _biffRecords.Take(listOffset).Sum(r => r.Length + 4);
        }

19 Source : AskerActor.cs
with Apache License 2.0
from Aaronontheweb

private void Asking()
        {
            // Time to place a new ask
            Receive<DoAsk>(_ =>
            {
                var ask = CreateAsk();
                _asks[ask.OrderId] = ask;
                _tradeGateway.Tell(new ConfirmableMessage<Ask>(ask, _confirmationId++, _traderId));
                _log.Info("ASK ${0} for {1} units of {2}", ask.AskPrice, ask.AskQuanreplacedy, _tickerSymbol);
            });

            Receive<Fill>(f => _asks.ContainsKey(f.OrderId), f =>
            {
                _fills.Add(f);
                _log.Info("Received FILL for ASK order {0} of {1} stock @ ${2} per unit for {3} units", f.OrderId, f.StockId, f.Price, f.Quanreplacedy);
                _log.Info("We have sold {0} units of {1} at AVG price of {2}", _fills.Sum(x => x.Quanreplacedy), _tickerSymbol, _fills.Average(x => (decimal)x.Quanreplacedy * x.Price));
            });
        }

19 Source : BidderActor.cs
with Apache License 2.0
from Aaronontheweb

private void Bidding()
        {
            // Time to place a new bid
            Receive<DoBid>(_ =>
            {
                var bid = CreateBid();
                _bids[bid.OrderId] = bid;
                _tradeGateway.Tell(new ConfirmableMessage<Bid>(bid, _confirmationId++, _traderId));
                _log.Info("BID ${0} for {1} units of {2}", bid.BidPrice, bid.BidQuanreplacedy, _tickerSymbol);
            });

            Receive<Fill>(f => _bids.ContainsKey(f.OrderId), f =>
            {
                _fills.Add(f);
                _log.Info("Received FILL for BID order {0} of {1} stock @ ${2} per unit for {3} units", f.OrderId, f.StockId, f.Price, f.Quanreplacedy);
                _log.Info("We now own {0} units of {1} at AVG price of {2}", _fills.Sum(x => x.Quanreplacedy), _tickerSymbol, _fills.Average(x => (decimal)x.Quanreplacedy * x.Price));
            });
        }

19 Source : CelPropertyDrawer.cs
with MIT License
from aarthificial

public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
        {
            float childPropertiesHeight = PropertiesToDraw.Sum(
                name => EditorGUI.GetPropertyHeight(property.FindPropertyRelative(name))
            );

            return Mathf.Max(childPropertiesHeight + Spacing * 6, Size) + Margin * 2;
        }

19 Source : GameUtils.cs
with Apache License 2.0
from AantCoder

public static int FindThings(ThingDef def, int destroy, bool getMaxByMap)
        {
            int countAll = 0;
            int countMax = 0;
            List<Pair<List<Thing>, int>> maps = new List<Pair<List<Thing>, int>>();
            for (int i = 0; i < Current.Game.Maps.Count; i++)
            {
                var m = Current.Game.Maps[i];
                if (m.IsPlayerHome)
                {
                    List<Thing> things = GameUtils.GetAllThings(m)
                        .Where(t => t.def == def).ToList();
                    var c = things.Sum(t => t.stackCount);
                    maps.Add(new Pair<List<Thing>, int>(things, c));
                    countAll += c;
                    if (countMax < c) countMax = c;
                }
            }
            int count = getMaxByMap ? countMax : countAll;
            if (destroy > 0 && destroy < count)
            {
                var destroyProcess = destroy;
                while (maps.Count > 0 && destroyProcess > 0)
                {
                    var m = maps.OrderByDescending(p => p.Second).First();
                    foreach (Thing thing in m.First)
                    {
                        if (thing.stackCount < destroyProcess)
                        {
                            destroyProcess -= thing.stackCount;
                            thing.Destroy();
                        }
                        else
                        {
                            thing.SplitOff(destroyProcess);
                            destroyProcess = 0;
                            break;
                        }
                    }
                }
            }
            return count;
        }

19 Source : MatchingEngine.cs
with Apache License 2.0
from Aaronontheweb

public OrderbookSnapshot GetSnapshot()
        {
            var snapshot = new OrderbookSnapshot(StockId, _timestamper.Now, AskTrades.Values.Sum(x => x.RemainingQuanreplacedy), BidTrades.Values.Sum(x => x.RemainingQuanreplacedy), 
                AsksByPrice.ToList(), BidsByPrice.ToList());
            return snapshot;
        }

19 Source : FdbKey.cs
with MIT License
from abdullin

[NotNull]
		public static Slice[] Merge(Slice prefix, [NotNull] Slice[] keys)
		{
			if (prefix == null) throw new ArgumentNullException("prefix");
			if (keys == null) throw new ArgumentNullException("keys");

			//REVIEW: merge this code with Slice.ConcatRange!

			// we can pre-allocate exactly the buffer by computing the total size of all keys
			int size = keys.Sum(key => key.Count) + keys.Length * prefix.Count;
			var writer = new SliceWriter(size);
			var next = new List<int>(keys.Length);

			//TODO: use multiple buffers if item count is huge ?

			foreach (var key in keys)
			{
				if (prefix.IsPresent) writer.WriteBytes(prefix);
				writer.WriteBytes(key);
				next.Add(writer.Position);
			}

			return FdbKey.SplitIntoSegments(writer.Buffer, 0, next);
		}

19 Source : CreateInvertedIndex.cs
with MIT License
from ABTSoftware

public static void CreateIndex(IEnumerable<KeyValuePair<Guid, Example>> examples)
        {
            var ex = examples.ToList();
            foreach (var example in ex)
            {
                string lines = GetTextFromExample(example.Value);
                var terms = GetTerms(lines);

                // Memory optimisation. Store term indices as ushort (16bit)
                if (terms.Count > ushort.MaxValue)
                    throw new InvalidOperationException("Too many terms in this example: " + example.Value.replacedle);

                var termDictExample = new Dictionary<string, List<ushort>>();
                for (ushort i = 0; i < terms.Count; i++)
                {
                    var term = terms[i];
                    if (termDictExample.ContainsKey(term))
                    {
                        termDictExample[term].Add(i);
                    }
                    else
                    {
                        termDictExample[term] = new List<ushort> { i };
                    }
                }

                var norm = Math.Sqrt(termDictExample.Sum(termDict => Sqr(termDict.Value.Count)));

                foreach (var termDict in termDictExample)
                {
                    var term = termDict.Key;
                    termDict.Value.TrimExcess();

                    if (_invertedIndex.ContainsKey(term))
                    {
                        var ti = new TermInfo(example.Key, termDict.Value.ToArray(), (float) (termDict.Value.Count / norm));
                        _invertedIndex[term].TermInfos.Add(ti);
                    }
                    else
                    {
                        _invertedIndex[term] = new Posting(new List<TermInfo>
                        {
                            new TermInfo(example.Key, termDict.Value.ToArray(), (float) (termDict.Value.Count/norm))
                        });
                    }
                    _invertedIndex[term].InvertedDoreplacedentFrequency += 1;
                }
            }

            _invertedIndex.ForEachDo(
                x => x.Value.InvertedDoreplacedentFrequency = Math.Log(ex.Count/x.Value.InvertedDoreplacedentFrequency));
        }

19 Source : CreateInvertedIndex.cs
with MIT License
from ABTSoftware

public static void CreateIndexForCode(IEnumerable<KeyValuePair<Guid, Example>> examples)
        {
            var ex = examples.ToList();

            foreach (var example in ex)
            {
                var tokenizer = new NGramTokenizer();

                string lines = GetSourceCodeFromExample(example.Value);
                var terms = lines.ToLower().Split(' ').Where(x => x != "")
                    .Select(tokenizer.Tokenize)
                    .SelectMany(strings => strings.SelectMany(inner => inner))                                        
                    .Select(sb => sb.ToString())
                    .Where(s => !string.IsNullOrEmpty(s) && s.Length > 1)
                    .ToList();

                // Memory optimisation. Store term indices as ushort (16bit)
                if (terms.Count > ushort.MaxValue)
                    throw new InvalidOperationException("Too many code terms for example: " + example.Value.replacedle);

                var termDictExample = new Dictionary<string, List<ushort>>();
                for (ushort i = 0; i < terms.Count; i++)
                {
                    var term = terms[i];
                    if (termDictExample.ContainsKey(term))
                    {
                        termDictExample[term].Add(i);
                    }
                    else
                    {
                        termDictExample[term] = new List<ushort> { i };
                    }
                }

                var norm = Math.Sqrt(termDictExample.Sum(termDict => Sqr(termDict.Value.Count)));

                foreach (var termDict in termDictExample)
                {
                    var term = termDict.Key;
                    var list = termDict.Value;

                    if (_codeInvertedIndex.ContainsKey(term))
                    {
                        var ti = new TermInfo(example.Key, termDict.Value.ToArray(), (float) (termDict.Value.Count / norm));
                        _codeInvertedIndex[term].TermInfos.Add(ti);
                    }
                    else
                    {
                        var ti = new TermInfo(example.Key, termDict.Value.ToArray(), (float)(termDict.Value.Count / norm));
                        _codeInvertedIndex[term] = new Posting(new List<TermInfo>
                        {
                            ti,
                        });
                    }
                    _codeInvertedIndex[term].InvertedDoreplacedentFrequency += 1;
                }
                
            }

            _codeInvertedIndex.ForEachDo(x =>
            {
                x.Value.InvertedDoreplacedentFrequency = Math.Log(ex.Count/x.Value.InvertedDoreplacedentFrequency);

                // Collapse memory of List<TermInfo>
                x.Value.TermInfos = x.Value.TermInfos.ToList();
            });
        }

19 Source : WorldDatabaseWithEntityCache.cs
with GNU Affero General Public License v3.0
from ACEmulator

private void TreasureMaterialBase_Normalize(Dictionary<int, Dictionary<int, List<TreasureMaterialBase>>> materialBase)
        {
            foreach (var kvp in materialBase)
            {
                var materialCode = kvp.Key;
                var tiers = kvp.Value;

                foreach (var kvp2 in tiers)
                {
                    var tier = kvp2.Key;
                    var list = kvp2.Value;

                    var totalProbability = list.Sum(i => i.Probability);

                    if (Math.Abs(1.0f - totalProbability) < NormalizeEpsilon)
                        continue;

                    //Console.WriteLine($"TotalProbability {totalProbability} found for TreasureMaterialBase {materialCode} tier {tier}");

                    var factor = 1.0f / totalProbability;

                    foreach (var item in list)
                        item.Probability *= factor;

                    /*totalProbability = list.Sum(i => i.Probability);

                    Console.WriteLine($"After: {totalProbability}");*/
                }
            }
        }

19 Source : WorldDatabaseWithEntityCache.cs
with GNU Affero General Public License v3.0
from ACEmulator

private void TreasureMaterialColor_Normalize(Dictionary<int, Dictionary<int, List<TreasureMaterialColor>>> materialColor)
        {
            foreach (var kvp in materialColor)
            {
                var material = kvp.Key;
                var colorCodes = kvp.Value;

                foreach (var kvp2 in colorCodes)
                {
                    var colorCode = kvp2.Key;
                    var list = kvp2.Value;

                    var totalProbability = list.Sum(i => i.Probability);

                    if (Math.Abs(1.0f - totalProbability) < NormalizeEpsilon)
                        continue;

                    //Console.WriteLine($"TotalProbability {totalProbability} found for TreasureMaterialColor {(MaterialType)material} ColorCode {colorCode}");

                    var factor = 1.0f / totalProbability;

                    foreach (var item in list)
                        item.Probability *= factor;

                    /*totalProbability = list.Sum(i => i.Probability);

                    Console.WriteLine($"After: {totalProbability}");*/
                }
            }
        }

19 Source : WorldDatabaseWithEntityCache.cs
with GNU Affero General Public License v3.0
from ACEmulator

private void TreasureMaterialGroups_Normalize(Dictionary<int, Dictionary<int, List<TreasureMaterialGroups>>> materialGroups)
        {
            foreach (var kvp in materialGroups)
            {
                var materialGroup = kvp.Key;
                var tiers = kvp.Value;

                foreach (var kvp2 in tiers)
                {
                    var tier = kvp2.Key;
                    var list = kvp2.Value;

                    var totalProbability = list.Sum(i => i.Probability);

                    if (Math.Abs(1.0f - totalProbability) < NormalizeEpsilon)
                        continue;

                    //Console.WriteLine($"TotalProbability {totalProbability} found for TreasureMaterialGroup {(MaterialType)materialGroup} tier {tier}");

                    var factor = 1.0f / totalProbability;

                    foreach (var item in list)
                        item.Probability *= factor;

                    /*totalProbability = list.Sum(i => i.Probability);

                    Console.WriteLine($"After: {totalProbability}");*/
                }
            }
        }

19 Source : Fellowship.cs
with GNU Affero General Public License v3.0
from ACEmulator

public void SplitXp(ulong amount, XpType xpType, ShareType shareType, Player player)
        {
            // https://asheron.fandom.com/wiki/Announcements_-_2002/02_-_Fever_Dreams#Letter_to_the_Players_1

            var fellowshipMembers = GetFellowshipMembers();

            shareType &= ~ShareType.Fellowship;

            // quest turn-ins: flat share (retail default)
            if (xpType == XpType.Quest && !PropertyManager.GetBool("fellow_quest_bonus").Item)
            {
                var perAmount = (long)amount / fellowshipMembers.Count;

                foreach (var member in fellowshipMembers.Values)
                {
                    var fellowXpType = player == member ? XpType.Quest : XpType.Fellowship;

                    member.GrantXP(perAmount, fellowXpType, shareType);
                }
            }

            // divides XP evenly to all the sharable fellows within level range,
            // but with a significant boost to the amount of xp, based on # of fellowship members
            else if (EvenShare)
            {
                var totalAmount = (ulong)Math.Round(amount * GetMemberSharePercent());

                foreach (var member in fellowshipMembers.Values)
                {
                    var shareAmount = (ulong)Math.Round(totalAmount * GetDistanceScalar(player, member, xpType));

                    var fellowXpType = player == member ? xpType : XpType.Fellowship;

                    member.GrantXP((long)shareAmount, fellowXpType, shareType);
                }

                return;
            }

            // divides XP to all sharable fellows within level range
            // based on each fellowship member's level
            else
            {
                var levelXPSum = fellowshipMembers.Values.Select(p => p.GetXPToNextLevel(p.Level.Value)).Sum();

                foreach (var member in fellowshipMembers.Values)
                {
                    var levelXPScale = (double)member.GetXPToNextLevel(member.Level.Value) / levelXPSum;

                    var playerTotal = (ulong)Math.Round(amount * levelXPScale * GetDistanceScalar(player, member, xpType));

                    var fellowXpType = player == member ? xpType : XpType.Fellowship;

                    member.GrantXP((long)playerTotal, fellowXpType, shareType);
                }
            }
        }

19 Source : AttackDamage.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static ulong GetTotalDamage(List<AttackDamage> attacks, WorldObject source)
        {
            return (ulong)attacks.Where(a => a.Source == source).Sum(a => a.Amount);
        }

19 Source : BodyPartTable.cs
with GNU Affero General Public License v3.0
from ACEmulator

public CombatBodyPart RollBodyPart(Quadrant quadrant)
        {
            var idx = (int)quadrant.GetIndex();

            var bodyParts = Quadrants[idx];

            var total = bodyParts.Sum(i => i.Probability);

            if (total == 0.0f)
                return CombatBodyPart.Undefined;

            var rng = ThreadSafeRandom.Next(0.0f, total);

            var totalProbability = 0.0f;
            foreach (var bodyPart in bodyParts)
            {
                totalProbability += bodyPart.Probability;
                if (rng < totalProbability)
                    return bodyPart.BodyPart;
            }
            return CombatBodyPart.Undefined;
        }

19 Source : Container.cs
with GNU Affero General Public License v3.0
from ACEmulator

public int GetNumInventoryItemsOfWCID(uint weenieClreplacedId)
        {
            return GetInventoryItemsOfWCID(weenieClreplacedId).Select(i => i.StackSize ?? 1).Sum();
        }

19 Source : Container.cs
with GNU Affero General Public License v3.0
from ACEmulator

public int GetNumInventoryItemsOfWeenieClreplaced(string weenieClreplacedName)
        {
            return GetInventoryItemsOfWeenieClreplaced(weenieClreplacedName).Select(i => i.StackSize ?? 1).Sum();
        }

19 Source : Monster_Awareness.cs
with GNU Affero General Public License v3.0
from ACEmulator

public Creature SelectWeightedDistance(List<TargetDistance> targetDistances)
        {
            if (targetDistances.Count == 1)
                return targetDistances[0].Target;

            // http://asheron.wikia.com/wiki/Wi_Flag

            var distSum = targetDistances.Select(i => i.Distance).Sum();

            // get the sum of the inverted ratios
            var invRatioSum = targetDistances.Count - 1;

            // roll between 0 - invRatioSum here,
            // instead of 0-1 (the source of the original wi bug)
            var rng = ThreadSafeRandom.Next(0.0f, invRatioSum);

            // walk the list
            var invRatio = 0.0f;
            foreach (var targetDistance in targetDistances)
            {
                invRatio += 1.0f - (targetDistance.Distance / distSum);

                if (rng < invRatio)
                    return targetDistance.Target;
            }
            // precision error?
            Console.WriteLine($"{Name}.SelectWeightedDistance: couldn't find target: {string.Join(",", targetDistances.Select(i => i.Distance))}");
            return targetDistances[0].Target;
        }

19 Source : Monster_Inventory.cs
with GNU Affero General Public License v3.0
from ACEmulator

public float GetTotalProbability(List<TreasureWielded> items)
        {
            if (items == null) return 0.0f;

            var prob = items.Select(i => i.Probability).ToList();

            var totalSum = prob.Sum();
            var totalProduct = prob.Product();

            return totalSum - totalProduct;
        }

19 Source : WorldObject_Set.cs
with GNU Affero General Public License v3.0
from ACEmulator

public static List<Spell> GetSpellSet(List<WorldObject> sereplacedems, int levelDiff = 0)
        {
            var spells = new List<Spell>();

            var firstSereplacedem = sereplacedems.FirstOrDefault();

            if (firstSereplacedem is null)
                return spells;

            var equipmentSet = firstSereplacedem.EquipmentSetId;
            var itemXpStyle = firstSereplacedem.ItemXpStyle ?? 0;

            if (!DatManager.PortalDat.SpellTable.SpellSet.TryGetValue((uint)equipmentSet, out var spellSet))
                return spells;

            // apply maximum level cap here?
            uint level = 0;
            if (itemXpStyle > 0)
                level = (uint)(sereplacedems.Sum(i => i.ItemLevel ?? 0) + levelDiff);
            else
                level = (uint)sereplacedems.Count;

            var highestTier = spellSet.HighestTier;

            //Console.WriteLine($"Total level: {level}");
            level = Math.Min(level, highestTier);

            if (!spellSet.SpellSetTiersNoGaps.TryGetValue(level, out var spellSetTiers))
                return spells;

            foreach (var spellId in spellSetTiers.Spells)
                spells.Add(new Spell(spellId, false));

            return spells;
        }

19 Source : EmployeeModel.cs
with MIT License
from Actipro

private void UpdateTotalTaskHours() {
			this.TotalTaskHours = tasks.OfType<ServiceModel>().Sum(o => o.Hours);
		}

19 Source : MainWindow.cs
with MIT License
from adainrivers

public void UpdateStatus()
        {
            if (_newWorldProcess == null || _newWorldProcess.HasExited)
            {
                NewWorldStatus.Text = NewWorldNotRunning;
                NewWorldStatus.ForeColor = Color.Red;
                TakeScreenshotButton.Enabled = false;
                TimerProcessRefresher.Enabled = true;
                _keyboardHooks.Stop();
            }
            else
            {
                NewWorldStatus.Text = NewWorldRunning;
                NewWorldStatus.ForeColor = Color.Green;
                TakeScreenshotButton.Enabled = true;
                TimerProcessRefresher.Enabled = false;
                _keyboardHooks.Start();
            }

            ExportPricesButton.Enabled = _prices.Count > 0;
            CapturedPricesCount.Text = _prices.Count.ToString();
            TotalItems.Text = _prices.Sum(p => p.Availability).ToString();
        }

19 Source : ShoppingCart.cs
with MIT License
from Adoxio

public decimal GetCartTotal()
		{
			var carreplacedems = GetCarreplacedems();

			var total = carreplacedems.Sum(item => item.Price == null ? 0 : item.Price.Value * item.Quanreplacedy);

			return total;
		}

19 Source : DataAdapterOrganizationServiceContextExtensions.cs
with MIT License
from Adoxio

public static IDictionary<Guid, ForumCounts> FetchForumCounts(this OrganizationServiceContext serviceContext, IEnumerable<Guid> forumIds)
		{
			if (!forumIds.Any())
			{
				return new Dictionary<Guid, ForumCounts>();
			}

			var ids = forumIds.ToArray();

			var fetchXml = XDoreplacedent.Parse(@"
				<fetch mapping=""logical"" aggregate=""true"">
					<enreplacedy name=""adx_communityforum"">
						<attribute name=""adx_communityforumid"" alias=""id"" groupby=""true""/>
						<filter type=""and""/>
						<link-enreplacedy name=""adx_communityforumthread"" from=""adx_forumid"" to=""adx_communityforumid"">
							<attribute name=""adx_communityforumthreadid"" alias=""threadid"" groupby=""true""/>
							<link-enreplacedy name=""adx_communityforumpost"" from=""adx_forumthreadid"" to=""adx_communityforumthreadid"">
								<attribute name=""adx_communityforumpostid"" alias=""postcount"" aggregate=""count""/>
							</link-enreplacedy>
						</link-enreplacedy>
					</enreplacedy>
				</fetch>");

			var filter = fetchXml.XPathSelectElement("//enreplacedy[@name='adx_communityforum']/filter");

			if (filter == null)
			{
				throw new InvalidOperationException(string.Format("Unable to select {0} element.", "adx_communityforum filter"));
			}

			filter.AddFetchXmlFilterInCondition("adx_communityforumid", ids.Select(id => id.ToString()));

			var fetch = Fetch.Parse(fetchXml.ToString());
			var response = (serviceContext as IOrganizationService).RetrieveMultiple(fetch);

			var results = response.Enreplacedies
				.GroupBy(e => (Guid)e.GetAttributeValue<AliasedValue>("id").Value, e => e)
				.Select(forumThreadGrouping => new KeyValuePair<Guid, ForumCounts>(
					forumThreadGrouping.Key,
					new ForumCounts(
						forumThreadGrouping.Count(),
						forumThreadGrouping.Sum(postCounts => postCounts.GetAttributeAliasedValue<int?>("postcount").GetValueOrDefault()))));

			var counts = ids.ToDictionary(id => id, id => new ForumCounts(0, 0));

			foreach (var result in results)
			{
				counts[result.Key] = result.Value;
			}

			return counts;
		}

19 Source : DataAdapterOrganizationServiceContextExtensions.cs
with MIT License
from Adoxio

public static ForumCounts FetchForumCountsForWebsite(this OrganizationServiceContext serviceContext, Guid websiteId)
		{
			var fetchXml = XDoreplacedent.Parse(@"
				<fetch mapping=""logical"" aggregate=""true"">
					<enreplacedy name=""adx_communityforum"">
						<attribute name=""adx_communityforumid"" alias=""id"" groupby=""true""/>
						<filter type=""and"">
							<condition attribute=""adx_websiteid"" operator=""eq"" />
						</filter>
						<link-enreplacedy name=""adx_communityforumthread"" from=""adx_forumid"" to=""adx_communityforumid"">
							<attribute name=""adx_communityforumthreadid"" alias=""threadid"" groupby=""true""/>
							<link-enreplacedy name=""adx_communityforumpost"" from=""adx_forumthreadid"" to=""adx_communityforumthreadid"">
								<attribute name=""adx_communityforumpostid"" alias=""postcount"" aggregate=""count""/>
							</link-enreplacedy>
						</link-enreplacedy>
					</enreplacedy>
				</fetch>");

			var websiteIdCondition = fetchXml.XPathSelectElement("//enreplacedy[@name='adx_communityforum']/filter/condition[@attribute='adx_websiteid']");

			if (websiteIdCondition == null)
			{
				throw new InvalidOperationException("Unable to select the adx_websiteid filter condition element.");
			}

			websiteIdCondition.SetAttributeValue("value", websiteId.ToString());

			var fetch = Fetch.Parse(fetchXml.ToString());
			var response = (serviceContext as IOrganizationService).RetrieveMultiple(fetch);

			var forumCounts = response.Enreplacedies
				.GroupBy(e => (Guid)e.GetAttributeValue<AliasedValue>("id").Value, e => e)
				.Select(forumThreadGrouping =>
					new ForumCounts(
						forumThreadGrouping.Count(),
						forumThreadGrouping.Sum(postCounts => postCounts.GetAttributeAliasedValue<int?>("postcount").GetValueOrDefault())))
				.ToArray();

			return new ForumCounts(forumCounts.Sum(c => c.ThreadCount), forumCounts.Sum(c => c.PostCount));
		}

19 Source : DataAdapterOrganizationServiceContextExtensions.cs
with MIT License
from Adoxio

public static ForumCounts FetchForumCountsForWebsiteWithTags(this OrganizationServiceContext serviceContext, Guid websiteId, string[] tags)
		{
			var fetchXml = XDoreplacedent.Parse(@"
				<fetch mapping=""logical"" aggregate=""true"">
					<enreplacedy name=""adx_communityforum"">
						<attribute name=""adx_communityforumid"" alias=""id"" groupby=""true""/>
						<filter type=""and"">
							<condition attribute=""adx_websiteid"" operator=""eq"" />
						</filter>
						<link-enreplacedy name=""adx_communityforumthread"" from=""adx_forumid"" to=""adx_communityforumid"">
							<attribute name=""adx_communityforumthreadid"" alias=""threadid"" groupby=""true""/>
							<link-enreplacedy name=""adx_communityforumpost"" from=""adx_forumthreadid"" to=""adx_communityforumthreadid"">
								<attribute name=""adx_communityforumpostid"" alias=""postcount"" aggregate=""count""/>
							</link-enreplacedy>
							<link-enreplacedy name=""adx_communityforumthread_tag"" from=""adx_communityforumthreadid"" to=""adx_communityforumthreadid"">
								<link-enreplacedy name=""adx_tag"" from=""adx_tagid"" to=""adx_tagid"">
									<filter type=""and"">
										<condition attribute=""adx_websiteid"" operator=""eq"" />
									</filter>
								</link-enreplacedy>
							</link-enreplacedy>
						</link-enreplacedy>
					</enreplacedy>
				</fetch>");

			var websiteIdConditions = fetchXml.XPathSelectElements("//filter/condition[@attribute='adx_websiteid']");

			foreach (var websiteIdCondition in websiteIdConditions)
			{
				websiteIdCondition.SetAttributeValue("value", websiteId.ToString());
			}

			var tagNameFilter = fetchXml.XPathSelectElement("//link-enreplacedy[@name='adx_tag']/filter[@type='and']");

			if (tagNameFilter == null)
			{
				throw new InvalidOperationException("Unable to select the tag name filter condition element.");
			}

			foreach (var tag in tags)
			{
				tagNameFilter.AddFetchXmlFilterCondition("adx_name", "eq", tag);
			}

			var fetch = Fetch.Parse(fetchXml.ToString());
			var response = (serviceContext as IOrganizationService).RetrieveMultiple(fetch);

			var forumCounts = response.Enreplacedies
				.GroupBy(e => (Guid)e.GetAttributeValue<AliasedValue>("id").Value, e => e)
				.Select(forumThreadGrouping =>
					new ForumCounts(
						forumThreadGrouping.Count(),
						forumThreadGrouping.Sum(postCounts => postCounts.GetAttributeAliasedValue<int?>("postcount").GetValueOrDefault())))
				.ToArray();

			return new ForumCounts(forumCounts.Sum(c => c.ThreadCount), forumCounts.Sum(c => c.PostCount));
		}

19 Source : ClonesManager.cs
with MIT License
from adrenak

private static long GetDirectorySize(DirectoryInfo directory, bool includeNested = false,
            string progressBarPrefix = "")
        {
            EditorUtility.DisplayProgressBar(progressBarPrefix + "Calculating size of directories...",
                "Scanning '" + directory.FullName + "'...", 0f);

            /// Calculate size of all files in directory.
            long filesSize = directory.GetFiles().Sum((FileInfo file) => file.Length);

            /// Calculate size of all nested directories.
            long directoriesSize = 0;
            if (includeNested)
            {
                IEnumerable<DirectoryInfo> nestedDirectories = directory.GetDirectories();
                foreach (DirectoryInfo nestedDir in nestedDirectories)
                {
                    directoriesSize += ClonesManager.GetDirectorySize(nestedDir, true, progressBarPrefix);
                }
            }

            return filesSize + directoriesSize;
        }

19 Source : ClientsViewModel.cs
with MIT License
from ahmed-abdelrazek

async Task DebitCredit()
        {
            decimal Debit = decimal.Round(Clients.Where(c => c.Balance > 0).Sum(i => i.Balance), 2);
            decimal Credit = decimal.Round(Clients.Where(c => c.Balance < 0).Sum(i => i.Balance), 2);
            await Task.Run(() =>
            {
                ClientCount = $"مجموع العملاء: {Clients.Count()}";
                ClientDebits = $"اجمالى لينا: {Math.Abs(Debit)}";
                ClientCredits = $"اجمالى علينا: {Math.Abs(Credit)}";
                ClientProfit = $"تقدير لصافى لينا: {Math.Abs(Debit) - Math.Abs(Credit)}";
            });
        }

19 Source : CompaniesViewModel.cs
with MIT License
from ahmed-abdelrazek

async Task DebitCredit()
        {
            decimal Debit = decimal.Round(Companies.Where(c => c.Balance < 0).Sum(i => i.Balance), 2);
            decimal Credit = decimal.Round(Companies.Where(c => c.Balance > 0).Sum(i => i.Balance), 2);

            await Task.Run(() =>
            {
                CompaniesCount = $"مجموع العملاء: {Companies.Count}";
                CompaniesDebits = $"اجمالى لينا: {Math.Abs(Debit)}";
                CompaniesCredits = $"اجمالى علينا: {Math.Abs(Credit)}";
                CompaniesProfit = $"تقدير لصافى لينا: {Math.Abs(Debit) - Math.Abs(Credit)}";
            });
        }

19 Source : ServicesViewModel.cs
with MIT License
from ahmed-abdelrazek

async Task DebitCredit()
        {
            decimal Debit = decimal.Round(Services.Where(c => c.Balance > 0).Sum(i => i.Balance), 2);
            await Task.Run(() =>
            {
                ServicesCount = $"مجموع الخدمات: {Services.Count()}";
                ServicesPurchasePrice = $"اجمالى لينا: {Math.Abs(Debit)}";
            });
        }

19 Source : SuppliersViewModel.cs
with MIT License
from ahmed-abdelrazek

async Task DebitCredit()
        {
            decimal Debit = decimal.Round(Suppliers.Where(c => c.Balance < 0).Sum(i => i.Balance), 2);
            decimal Credit = decimal.Round(Suppliers.Where(c => c.Balance > 0).Sum(i => i.Balance), 2);
            await Task.Run(() =>
            {
                SuppliersCount = $"مجموع العملاء: {Suppliers.Count()}";
                SuppliersDebits = $"اجمالى لينا: {Math.Abs(Debit)}";
                SuppliersCredits = $"اجمالى علينا: {Math.Abs(Credit)}";
                SuppliersProfit = $"تقدير لصافى لينا: {Math.Abs(Debit) - Math.Abs(Credit)}";
            });
        }

19 Source : CardsViewModel.cs
with MIT License
from ahmed-abdelrazek

public async Task OnLoadedAsync()
        {
            await Task.Run(() =>
            {
                using (var db = new LiteDatabase(Properties.Settings.Default.LiteDbConnectionString))
                {
                    Companies = new ObservableCollection<Company>(db.GetCollection<Company>(DBCollections.Companies).FindAll().ToList());
                    Suppliers = new ObservableCollection<Supplier>(db.GetCollection<Supplier>(DBCollections.Suppliers).FindAll().ToList());
                    Cards = new ObservableCollection<Item>(db.GetCollection<Item>(DBCollections.Items.ToString()).Find(i => i.Group == ItemGroup.Card).ToList());
                }

                CardsCount = $"إجمالى الكروت: {Cards.Count()}";
                CardsPurchasePrice = $"اجمالى سعر الشراء: {decimal.Round(Cards.Sum(i => i.PurchasePrice * i.QTY), 2)}";
                CardsSalePrice = $"اجمالى سعر البيع: {decimal.Round(Cards.Sum(i => i.RetailPrice * i.QTY), 2)}";
                CardsProfit = $"تقدير صافى الربح: {decimal.Round((Cards.Sum(i => i.RetailPrice * i.QTY) - Cards.Sum(i => i.PurchasePrice * i.QTY)), 2)}";
            });
        }

19 Source : ItemsViewModel.cs
with MIT License
from ahmed-abdelrazek

public async Task OnLoadedAsync()
        {
            await Task.Run(() =>
            {
                using (var db = new LiteDatabase(Properties.Settings.Default.LiteDbConnectionString))
                {
                    Companies = new ObservableCollection<Company>(db.GetCollection<Company>(DBCollections.Companies).FindAll());
                    Suppliers = new ObservableCollection<Supplier>(db.GetCollection<Supplier>(DBCollections.Suppliers).FindAll());
                    Items = new ObservableCollection<Item>(db.GetCollection<Item>(DBCollections.Items).Find(i => i.Group == ItemGroup.Other));
                }
            });

            await Task.Run(() =>
            {
                ItemsCount = $"إجمالى الاصناف: {Items.Count}";
                ItemsPurchasePrice = $"اجمالى سعر الشراء: {decimal.Round(Items.Sum(i => i.PurchasePrice * i.QTY), 2)}";
                ItemsSalePrice = $"اجمالى سعر البيع: {decimal.Round(Items.Sum(i => i.RetailPrice * i.QTY), 2)}";
                ItemsProfit = $"تقدير صافى الربح: {decimal.Round(Items.Sum(i => i.RetailPrice * i.QTY) - Items.Sum(i => i.PurchasePrice * i.QTY), 2)}";
            });
        }

19 Source : SalesMenViewModel.cs
with MIT License
from ahmed-abdelrazek

async Task DebitCredit()
        {
            await Task.Run(() =>
            {
                decimal Debit = decimal.Round(SalesMen.Where(c => c.Balance < 0).Sum(i => i.Balance), 2);
                decimal Credit = decimal.Round(SalesMen.Where(c => c.Balance > 0).Sum(i => i.Balance), 2);

                SalesMenCount = $"مجموع العملاء: {SalesMen.Count}";
                SalesMenDebits = $"اجمالى لينا: {Math.Abs(Debit)}";
                SalesMenCredits = $"اجمالى علينا: {Math.Abs(Credit)}";
                SalesMenProfit = $"تقدير لصافى لينا: {Math.Abs(Debit) - Math.Abs(Credit)}";
            });
        }

19 Source : LinqSample.cs
with The Unlicense
from ahotko

private void SumAgeSimple()
        {
            int sumAge = _sampleList.Select(x => x.Age).Sum();
            Console.WriteLine($"Sum with Select = {sumAge}");
            //...or...
            sumAge = _sampleList.Sum(x => x.Age);
            Console.WriteLine($"Sum without Select = {sumAge}");
        }

19 Source : LinqSample.cs
with The Unlicense
from ahotko

private void SumAgeByLastnameGrouping()
        {
            var ageLastnameGroups =
                from sample in _sampleList
                group sample by sample.LastName into sampleGroup
                select
                new
                {
                    Group = sampleGroup.Key,
                    SumAge = sampleGroup.Sum(x => x.Age),
                    CountMembers = sampleGroup.Count()
                };
            //use result
            foreach (var sample in ageLastnameGroups)
            {
                Console.WriteLine($"Lastname = {sample.Group}, {sample.CountMembers} member(s), SumAge = {sample.SumAge}");
            }
        }

19 Source : LinqSample.cs
with The Unlicense
from ahotko

private void SumAgeByLastnameGroupingOrderedDescending()
        {
            var ageLastnameGroups =
                (from sample in _sampleList
                 group sample by sample.LastName into sampleGroup
                 select
                 new
                 {
                     Group = sampleGroup.Key,
                     SumAge = sampleGroup.Sum(x => x.Age),
                     CountMembers = sampleGroup.Count()
                 }).OrderByDescending(x => x.CountMembers);
            //use result
            foreach (var sample in ageLastnameGroups)
            {
                Console.WriteLine($"Lastname = {sample.Group}, {sample.CountMembers} member(s), SumAge = {sample.SumAge}");
            }
        }

19 Source : LinqSample.cs
with The Unlicense
from ahotko

private void SumAgeByLastnameAndPlaceGrouping()
        {
            var ageLastnameGroups =
                from sample in _sampleList
                group sample by new { sample.LastName, sample.Place } into sampleGroup
                select
                new
                {
                    GroupingKey = sampleGroup.Key,
                    SumAge = sampleGroup.Sum(x => x.Age),
                    CountMembers = sampleGroup.Count()
                };
            //use result
            foreach (var sample in ageLastnameGroups)
            {
                Console.WriteLine($"Lastname = {sample.GroupingKey.LastName}, Place = {sample.GroupingKey.Place}, {sample.CountMembers} member(s), SumAge = {sample.SumAge}");
            }
        }

19 Source : LinqSample.cs
with The Unlicense
from ahotko

private void SumAgeByLastnameAndPlaceGroupingWithLet()
        {
            var ageLastnameGroups =
                from sample in _sampleList
                group sample by new 
                { 
                    sample.LastName, 
                    sample.Place
                } 
                into sampleGroup
                let sumAge = sampleGroup.Sum(x => x.Age)
                let memberCount = sampleGroup.Count()
                select
                new
                {
                    GroupingKey = sampleGroup.Key,
                    SumAge = sumAge,
                    CountMembers = memberCount
                };
            //use result
            foreach (var sample in ageLastnameGroups)
            {
                Console.WriteLine($"Lastname = {sample.GroupingKey.LastName}, Place = {sample.GroupingKey.Place}, {sample.CountMembers} member(s), SumAge = {sample.SumAge}");
            }
        }

19 Source : LinqSample.cs
with The Unlicense
from ahotko

private void SumAgeByLastnameAndPlaceGroupingOrdered()
        {
            var ageLastnameGroups =
                (from sample in _sampleList
                 group sample by new { sample.LastName, sample.Place } into sampleGroup
                 select
                 new
                 {
                     GroupingKey = sampleGroup.Key,
                     SumAge = sampleGroup.Sum(x => x.Age),
                     CountMembers = sampleGroup.Count()
                 }).OrderBy(x => x.CountMembers);
            //use result
            foreach (var sample in ageLastnameGroups)
            {
                Console.WriteLine($"Lastname = {sample.GroupingKey.LastName}, Place = {sample.GroupingKey.Place}, {sample.CountMembers} member(s), SumAge = {sample.SumAge}");
            }
        }

19 Source : LinqSample.cs
with The Unlicense
from ahotko

private void SumAgeByLastnameAndPlaceGroupingOrderedTop5()
        {
            var ageLastnameGroups =
                (from sample in _sampleList
                 group sample by new { sample.LastName, sample.Place } into sampleGroup
                 select
                 new
                 {
                     GroupingKey = sampleGroup.Key,
                     SumAge = sampleGroup.Sum(x => x.Age),
                     CountMembers = sampleGroup.Count()
                 }).OrderByDescending(x => x.CountMembers).Take(5);
            //use result
            foreach (var sample in ageLastnameGroups)
            {
                Console.WriteLine($"Lastname = {sample.GroupingKey.LastName}, Place = {sample.GroupingKey.Place}, {sample.CountMembers} member(s), SumAge = {sample.SumAge}");
            }
        }

19 Source : LinqSample.cs
with The Unlicense
from ahotko

private void SumAgeByLastnameAndPlaceGroupingOrderedSecond5()
        {
            var ageLastnameGroups =
                (from sample in _sampleList
                 group sample by new { sample.LastName, sample.Place } into sampleGroup
                 select
                 new
                 {
                     GroupingKey = sampleGroup.Key,
                     SumAge = sampleGroup.Sum(x => x.Age),
                     CountMembers = sampleGroup.Count()
                 }).OrderByDescending(x => x.CountMembers).Skip(5).Take(5);
            //use result
            foreach (var sample in ageLastnameGroups)
            {
                Console.WriteLine($"Lastname = {sample.GroupingKey.LastName}, Place = {sample.GroupingKey.Place}, {sample.CountMembers} member(s), SumAge = {sample.SumAge}");
            }
        }

19 Source : LinqSample.cs
with The Unlicense
from ahotko

private void SumAgeByLastnameAndPlaceGroupingOrderedLast5()
        {
            var ageLastnameGroups =
                (from sample in _sampleList
                 group sample by new { sample.LastName, sample.Place } into sampleGroup
                 select
                 new
                 {
                     GroupingKey = sampleGroup.Key,
                     SumAge = sampleGroup.Sum(x => x.Age),
                     CountMembers = sampleGroup.Count()
                 }).OrderByDescending(x => x.CountMembers);
            var last5AgeLastnameGroups = ageLastnameGroups.Skip(Math.Max(0, ageLastnameGroups.Count() - 5));
            //use result
            foreach (var sample in last5AgeLastnameGroups)
            {
                Console.WriteLine($"Lastname = {sample.GroupingKey.LastName}, Place = {sample.GroupingKey.Place}, {sample.CountMembers} member(s), SumAge = {sample.SumAge}");
            }
        }

19 Source : LinqSample.cs
with The Unlicense
from ahotko

private void SumAgeByLastnameAndPlaceGroupingOrderedTwice()
        {
            var ageLastnameGroups =
                (from sample in _sampleList
                 group sample by new { sample.LastName, sample.Place } into sampleGroup
                 select
                 new
                 {
                     GroupingKey = sampleGroup.Key,
                     SumAge = sampleGroup.Sum(x => x.Age),
                     CountMembers = sampleGroup.Count()
                 }).OrderBy(x => x.GroupingKey.Place).ThenBy(x => x.CountMembers);
            //use result
            foreach (var sample in ageLastnameGroups)
            {
                Console.WriteLine($"Lastname = {sample.GroupingKey.LastName}, Place = {sample.GroupingKey.Place}, {sample.CountMembers} member(s), SumAge = {sample.SumAge}");
            }
        }

19 Source : Modules.cs
with BSD 3-Clause "New" or "Revised" License
from airzero24

public static byte[] Combine(params byte[][] arrays)
        {
            byte[] rv = new byte[arrays.Sum(a => a.Length)];
            int offset = 0;
            foreach (byte[] array in arrays)
            {
                Buffer.BlockCopy(array, 0, rv, offset, array.Length);
                offset += array.Length;
            }
            return rv;
        }

See More Examples