本文整理汇总了C#中IEnumerable.FirstOrDefault方法的典型用法代码示例。如果您正苦于以下问题:C# IEnumerable.FirstOrDefault方法的具体用法?C# IEnumerable.FirstOrDefault怎么用?C# IEnumerable.FirstOrDefault使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IEnumerable
的用法示例。
在下文中一共展示了IEnumerable.FirstOrDefault方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateStaff
public ActionResult CreateStaff(IEnumerable<StaffView> staffs)
{
//產生加密誤密碼字串
String sPwd = oDB.EncryptString(staffs.FirstOrDefault().DecryptionPassword);
try
{
if (ModelState.IsValid)
{
var staff = new Staff
{
Account = staffs.FirstOrDefault().Account,
Name = staffs.FirstOrDefault().Name,
Password = sPwd,
DecryptionPassword = staffs.FirstOrDefault().DecryptionPassword,
Role = staffs.FirstOrDefault().Role
};
if (TryUpdateModel(staff))
{
db.Staff.Add(staff);
db.SaveChanges();
}
}
}
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
};
return Json(null);
}
示例2: UnionEnumerableExpressions
public static Expression UnionEnumerableExpressions(IEnumerable<Expression> expressions)
{
var count = expressions.Count();
if (count == 1) return expressions.FirstOrDefault();
else if(count >= 2)
{
var expressionGroups = expressions.GroupBy(x => x.Type);
if( expressionGroups.Count() != 1 ) throw new Exception("All expressions must be of the same type");
var elementType = ReduceExpressionGeneration.GetTypeOfEnumerable( expressionGroups.First().Key );
var unionInfos = typeof(Enumerable).GetMethods().Where(x => x.Name == "Union");
var unionInfo = unionInfos.FirstOrDefault();
var mi = unionInfo.MakeGenericMethod(elementType);
var first = expressions.FirstOrDefault();
var result = UnionEnumerableExpressions(expressions.Skip(1));
return Expression.Call
(
method: mi,
arg0: first,
arg1: result
);
}
else
{
return null;
}
}
示例3: Manager
/// <summary>
/// Constructor
/// </summary>
/// <param name="Profilers">The profilers.</param>
public Manager(IEnumerable<IProfiler> Profilers)
{
Contract.Requires<ArgumentNullException>(Profilers != null, "Profilers");
Profiler = Profilers.FirstOrDefault(x => !x.GetType().Namespace.StartsWith("UTILITIES", StringComparison.OrdinalIgnoreCase));
if (Profiler == null)
Profiler = Profilers.FirstOrDefault(x => x.GetType().Namespace.StartsWith("UTILITIES", StringComparison.OrdinalIgnoreCase));
}
示例4: findMatch
private IFubuFile findMatch(IEnumerable<IFubuFile> files, string search)
{
var exactMatch = files.FirstOrDefault(x => x.RelativePath == search);
if (exactMatch != null) return exactMatch;
return files.FirstOrDefault(x => x.RelativePath.EndsWith(search));
}
示例5: FindTypeMember
private static MemberInfo FindTypeMember(IEnumerable<MemberInfo> modelProperties, IEnumerable<MethodInfo> getMethods, string nameToSearch, IMappingOptions mappingOptions)
{
MemberInfo pi = modelProperties.FirstOrDefault(prop => NameMatches(prop.Name, nameToSearch));
if (pi != null)
return pi;
MethodInfo mi = getMethods.FirstOrDefault(m => NameMatches(m.Name, nameToSearch));
if (mi != null)
return mi;
pi = modelProperties.FirstOrDefault(prop => NameMatches(mappingOptions.SourceMemberNameTransformer(prop.Name), nameToSearch));
if (pi != null)
return pi;
mi = getMethods.FirstOrDefault(m => NameMatches(mappingOptions.SourceMemberNameTransformer(m.Name), nameToSearch));
if (mi != null)
return mi;
pi = modelProperties.FirstOrDefault(prop => NameMatches(prop.Name, mappingOptions.DestinationMemberNameTransformer(nameToSearch)));
if (pi != null)
return pi;
pi = getMethods.FirstOrDefault(m => NameMatches(m.Name, mappingOptions.DestinationMemberNameTransformer(nameToSearch)));
if (pi != null)
return pi;
return null;
}
示例6: TransactionDetailsViewItem
public TransactionDetailsViewItem(Model.Transaction transaction,
IEnumerable<Model.TransactionItem> transactionItems,
IEnumerable<Model.TransactionIgnoredItem> transactionIgnoredItems,
IEnumerable<Model.License> domainlessLicenseQuery,
IEnumerable<Model.License> customerapplessLicenseQuery)
: base(transaction)
{
PurchaserEmail = transaction.PurchaserEmail;
PurchaserName = (transactionItems.Any(l => l.License != null)) ?
transactionItems.FirstOrDefault().License.PurchasingCustomer.Name : transaction.PurchaserName;
OwnerName = (transactionItems.Any(l => l.License != null)) ?
transactionItems.FirstOrDefault().License.OwningCustomer.Name : "None";
SKUSummary = (from x in transactionItems select x.Sku).ToSummary(x => x.SkuCode, 99, ", ");
IgnoredSummary = (from x in transactionIgnoredItems select x.Description).ToSummary(x => x, 99, ", ");
StatusName = transaction.Status.GetDescription<Model.TransactionStatus>();
DomainlessLicenses = (from x in domainlessLicenseQuery select x.ObjectId).ToList();
CustomerapplessLicenses = (from x in customerapplessLicenseQuery select x.ObjectId).ToList();
}
示例7: GetValueSomewhereInThePage
private string GetValueSomewhereInThePage(HtmlNode document, string[] names, IEnumerable<HtmlNode> metaTags)
{
string result = null;
var possibleNames = names.SelectMany(n => new[] { n, "og:" + n });
var metaField = metaTags.FirstOrDefault(m => m.HasAttribute("property") && possibleNames.Contains(m.GetAttributeValue("property")));
if (metaField == null)
{
metaField = metaTags.FirstOrDefault(m => m.HasAttribute("name") && possibleNames.Contains(m.GetAttributeValue("name")));
}
if (metaField != null)
{
result = metaField.GetAttributeValue("content");
}
if (String.IsNullOrWhiteSpace(result))
{
foreach (var name in possibleNames)
{
var hiddenField = document.FindHiddenField(name);
if (hiddenField != null)
{
result = hiddenField.GetAttributeValue("value");
break;
}
}
}
return result;
}
示例8: Query
public IPagedList<OrderQueryModel> Query(IEnumerable<ExtendedQueryParameter> parameters, ICommerceDatabase db, int pageIndex, int pageSize)
{
if (pageIndex <= 1)
pageIndex = 1;
int num = 10;
var numPara = parameters.FirstOrDefault(o => o.Name == "Num");
if (numPara != null && numPara.Value != null && !string.IsNullOrEmpty(numPara.Value.ToString()))
num = Convert.ToInt32(numPara.Value);
decimal totalPrice = 100.0m;
var totalPara = parameters.FirstOrDefault(o => o.Name == "TotalPrice");
if (totalPara != null && totalPara.Value != null && !string.IsNullOrEmpty(totalPara.Value.ToString()))
totalPrice = Convert.ToDecimal(totalPara.Value);
var customerQuery = db.GetRepository<Customer>().Query();
IQueryable<OrderQueryModel> query = db.GetRepository<Order>().Query()
.Join(customerQuery,
order => order.CustomerId,
customer => customer.Id,
(order, customer) => new { Order = order, Customer = customer })
.Select(o => new OrderQueryModel() { Customer = o.Customer, Order = o.Order })
.Where(o => o.Order.Total > totalPrice)
.OrderByDescending(o => o.Order.Total);
var total = query.Count();
var data = query.Skip(0).Take(num).ToArray();
return new PagedList<OrderQueryModel>(data, pageIndex, pageSize, total);
}
示例9: ReplaceColor
private static void ReplaceColor( BaseBrush in_Brush, IEnumerable<ColorPair> in_Colors )
{
if( (in_Brush == null) || (in_Colors == null) )
return;
if( in_Colors.Count( ) == 0 )
return;
if( in_Brush is NGraphics.Models.Brushes.GradientBrush )
{
GradientBrush typedBrush = in_Brush as GradientBrush;
foreach( GradientStop stop in typedBrush.Stops )
{
ColorPair pair = in_Colors.FirstOrDefault(x => (stop.Color.Red == x.OldColor.R) && (stop.Color.Green == x.OldColor.G) && (stop.Color.Blue == x.OldColor.B) && (stop.Color.Alpha == x.OldColor.A));
if( pair != null )
stop.Color = new NGraphics.Models.Color(pair.NewColor.R, pair.NewColor.G, pair.NewColor.B, pair.NewColor.A);
}
}
else if( in_Brush is NGraphics.Models.Brushes.SolidBrush )
{
SolidBrush typedBrush = in_Brush as SolidBrush;
ColorPair pair = in_Colors.FirstOrDefault(x => (typedBrush.Color.Red == x.OldColor.R) && (typedBrush.Color.Green == x.OldColor.G) && (typedBrush.Color.Blue == x.OldColor.B) && (typedBrush.Color.Alpha == x.OldColor.A));
if( pair != null )
typedBrush.Color = new NGraphics.Models.Color(pair.NewColor.R, pair.NewColor.G, pair.NewColor.B, pair.NewColor.A);
}
}
示例10: MapGameInfo
public GameInfoViewModel MapGameInfo(GameDb game, IEnumerable<TeamDb> teams, Dictionary<string, string> users)
{
var result = new GameInfoViewModel();
var homeTeam = teams.FirstOrDefault(x => x.EntityId == game.HomeTeam.Id);
if (homeTeam != null)
{
result.HomeTeamName = homeTeam.Name;
result.HomeTeamMediaId = homeTeam.MediaId;
result.HomeTeamScore = game.HomeTeam.Score;
if (!string.IsNullOrEmpty(game.HomeTeam.BestMemberId))
result.HomeTeamBestPlayer = users[game.HomeTeam.BestMemberId];
result.HomeTeamScores = game
.HomeTeam.Members
.Where(x => x.Help != 0 || x.Score != 0)
.Select(x => MapGameInfoMember(x, users));
}
var guestTeam = teams.FirstOrDefault(x => x.EntityId == game.GuestTeam.Id);
if (guestTeam != null)
{
result.GuestTeamName = guestTeam.Name;
result.GuestTeamMediaId = guestTeam.MediaId;
result.GuestTeamScore = game.GuestTeam.Score;
if (!string.IsNullOrEmpty(game.GuestTeam.BestMemberId))
result.GuestTeamBestPlayer = users[game.GuestTeam.BestMemberId];
result.GuestTeamScores = game
.GuestTeam.Members
.Where(x => x.Help != 0 || x.Score != 0)
.Select(x => MapGameInfoMember(x, users));
}
return result;
}
示例11: GetName
private string GetName(IEnumerable<IRunElement> elements)
{
List<string> clues = new List<string>();
var host = elements.FirstOrDefault(e => e is BaseHostElement);
if (host != null)
{
clues.Add(host.Name);
}
var trace = elements.FirstOrDefault(e => e is TraceElement);
if (trace != null)
{
clues.Add(trace.Name);
}
var name = string.Join(" ", clues);
if (string.IsNullOrEmpty(name))
{
name = "Unknown";
}
return name;
}
示例12: FromClaims
public static ClaimsPrincipal FromClaims(IEnumerable<Claim> claims, bool allowMissing = false)
{
var amr = claims.FirstOrDefault(c => c.Type == JwtClaimTypes.AuthenticationMethod);
var sub = claims.FirstOrDefault(c => c.Type == JwtClaimTypes.Subject);
var idp = claims.FirstOrDefault(c => c.Type == JwtClaimTypes.IdentityProvider);
var authTime = claims.FirstOrDefault(c => c.Type == JwtClaimTypes.AuthenticationTime);
var id = new ClaimsIdentity(Constants.BuiltInIdentityProvider);
if (sub != null)
{
id.AddClaim(sub);
}
else
{
if (allowMissing == false)
{
throw new InvalidOperationException("sub claim is missing");
}
}
if (amr != null)
{
id.AddClaim(amr);
}
else
{
if (allowMissing == false)
{
throw new InvalidOperationException("amr claim is missing");
}
}
if (idp != null)
{
id.AddClaim(idp);
}
else
{
if (allowMissing == false)
{
throw new InvalidOperationException("idp claim is missing");
}
}
if (authTime != null)
{
id.AddClaim(authTime);
}
else
{
if (allowMissing == false)
{
throw new InvalidOperationException("auth_time claim is missing");
}
}
return new ClaimsPrincipal(id);
}
示例13: CreateConnectionString
private static ConnectionStringSettings CreateConnectionString(IEnumerable<Claim> claims)
{
string dblogin = claims.FirstOrDefault(c => c.Type == "dblogin").Value;
string dbpass = claims.FirstOrDefault(c => c.Type == "dbpass").Value;
string dbname = claims.FirstOrDefault(c => c.Type == "dbname").Value;
return Database.CreateConnectionString("System.Data.SqlClient", @"LUNALAPPY\SQLEXPRESS", Cryptography.Decrypt(dbname), Cryptography.Decrypt(dblogin), Cryptography.Decrypt(dbpass));
}
示例14: ModifyMetadata
public override void ModifyMetadata(EPiServer.Shell.ObjectEditing.ExtendedMetadata metadata,
IEnumerable<Attribute> attributes)
{
base.ModifyMetadata(metadata, attributes);
var groupKeyAttribute = attributes.FirstOrDefault(a => typeof (TagsGroupKeyAttribute) == a.GetType()) as TagsGroupKeyAttribute;
var cultureSpecificAttribute = attributes.FirstOrDefault(a => typeof(CultureSpecificAttribute) == a.GetType()) as CultureSpecificAttribute;
EditorConfiguration["GroupKey"] = Helpers.TagsHelper.GetGroupKeyFromAttributes(groupKeyAttribute, cultureSpecificAttribute);
}
示例15: WriteEntry
private static void WriteEntry(QueueEntry e, IEnumerable<Argument> arguments)
{
bool printProjectString = arguments.FirstOrDefault(a => a.Type == ArgumentType.PrintProjectString) != null ? true : false;
bool showAll = arguments.FirstOrDefault(a => a.Type == ArgumentType.ShowAll) != null ? true : false;
Console.Write(" Index {0}: {1}", e.Index, e.EntryStatusLiteral);
if (e.SpeedFactor == 0)
{
Console.WriteLine();
}
else
{
Console.WriteLine(" {0} X min speed", e.SpeedFactor);
}
Console.WriteLine(" server: {0}:{1}; project: {2}", e.ServerIP, e.ServerPort, e.ProjectID);
string misc4aEndian = e.Misc4aBigEndian ? "be" : "le";
Console.WriteLine(" Folding: run {0}, clone {1}, generation {2}; benchmark {3}; misc: {4}, {5}, {6} ({7})",
e.ProjectRun, e.ProjectClone, e.ProjectGen, e.Benchmark, e.Misc1a, e.Misc1b, e.Misc4a, misc4aEndian);
if (printProjectString)
{
Console.WriteLine(" Project: {0} (Run {1}, Clone {2}, Gen {3})", e.ProjectID, e.ProjectRun, e.ProjectClone, e.ProjectGen);
}
Console.WriteLine(" issue: {0:ddd MMM dd HH:mm:ss yyyy}; begin: {1:ddd MMM dd HH:mm:ss yyyy}", e.ProjectIssuedLocal, e.BeginTimeLocal);
Console.Write(" ");
if (e.EntryStatus == 3 || e.EntryStatus == 7)
{
Console.Write("end: {0:ddd MMM dd HH:mm:ss yyyy}; ", e.EndTimeLocal);
}
TimeSpan preferred = e.DueTimeLocal.Subtract(e.BeginTimeLocal);
Console.WriteLine("due: {0:ddd MMM dd HH:mm:ss yyyy} ({1} days)", e.DueTimeLocal, Math.Ceiling(preferred.TotalDays));
Console.WriteLine(" core URL: {0}", e.CoreDownloadUrl);
Console.Write(" core number: 0x{0}", e.CoreNumber);
Console.WriteLine("; core name: {0}", e.CoreName);
Console.WriteLine(" CPU: {0},{1} {2}; OS: {3},{4} {5}", e.CpuType, e.CpuSpecies, e.CpuString, e.OsType, e.OsSpecies, e.OsString);
Console.WriteLine(" smp cores: {0}; cores to use: {1}", e.NumberOfSmpCores, e.UseCores);
Console.WriteLine(" tag: {0}", e.WorkUnitTag);
if (e.Passkey.Length != 0 && showAll)
{
Console.WriteLine(" passkey: {0}", e.Passkey);
}
Console.WriteLine(" flops: {0} ({1:0.000000} megaflops)", e.Flops, e.MegaFlops);
Console.WriteLine(" memory: {0} MB", e.Memory);
Console.WriteLine(" client type: {0} {1}", e.RequiredClientType, e.RequiredClientTypeLiteral);
string assignmentInfoEndian = e.AssignmentInfoBigEndian ? "be" : "le";
if (e.AssignmentInfoPresent)
{
Console.WriteLine(" assignment info ({0}): {1:ddd MMM dd HH:mm:ss yyyy}; {2}", assignmentInfoEndian, e.AssignmentTimeStampLocal, e.AssignmentInfoChecksum);
}
Console.Write(" CS: {0}; ", e.CollectionServerIP);
if (e.NumberOfUploadFailures != 0)
{
Console.Write("upload failures: {0}; ", e.NumberOfUploadFailures);
}
Console.WriteLine("P limit: {0}", e.PacketSizeLimit);
Console.WriteLine(" user: {0}; team: {1}; ID: {2}; mach ID: {3}", e.FoldingID, e.Team, e.ID, e.MachineID);
Console.WriteLine(" work/wudata_{0:00}.dat file size: {1}; WU type: {2}", e.Index, e.WuDataFileSize, e.WorkUnitType);
}