我有一个通用的项目清单.每个项目都包含一个DateTime字段.我想以最优雅,最有效的方式使用Linq找到列表中的最新项目.
在我的情况下,优雅比效率更重要,但是以有效的方式做这件事也会很好.
谢谢.
阅读答案后:这是代码(和我喜欢的答案):
using System.Collections.Generic;
using System.Linq;
class Item
{
public Item Date { get; set; }
public string Name { get; set; }
}
static void Main(string[] args)
{
List<Item> items = CreateItems();
Item newest;
if (items.Count == 0)
newest = null;
else
newest = items.OrderByDescending(item => item.Date).First();
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试为WPF ItemContainerStyle编写可重用的模板.
此模板更改TabControl项目的外观.此模板旨在用于应用程序中的多个位置.
在每个地方使用它我希望能够传递不同的参数.例如:要更改项目边框的边距:
<Style x:Key="TabItemStyle1" TargetType="{x:Type TabItem}">
<Setter Property="Margin" Value="10,0"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<Grid SnapsToDevicePixels="true">
<Border x:Name="Bd" Width="80"
Background="Gray"
Margin="{TemplateBinding Margin}">
<ContentPresenter x:Name="Content"
ContentSource="Header" />
</Border>
</Grid>
<ControlTemplate.Triggers>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
...
<TabControl ItemContainerStyle="{DynamicResource TabItemStyle1}">
Run Code Online (Sandbox Code Playgroud)
在使用样式的地方我想写下这样的东西:
ItemContainerStyle="{DynamicResource TabItemStyle1 Margin='5,0'}"
Run Code Online (Sandbox Code Playgroud)
要么
<TabControl Margin="78,51,167,90" ItemContainerStyle="{DynamicResource TabItemStyle1}"
ItemContainerStyle.Margin="5,0">
Run Code Online (Sandbox Code Playgroud)
动机是在具有不同边距的不同位置使用此模板.有没有办法做到这一点 ?
谢谢
我想使用泛型类并强制其中一个参数派生自某个基类.就像是:
public class BaseClass { }
public class DerivedClass : BaseClass { }
public class Manager<T> where T : derivesfrom(BaseClass)
Run Code Online (Sandbox Code Playgroud)
我现在这样做的方式是在运行时在构造函数中:
public class Manager<T> where T : class
{
public Manager()
{
if (!typeof(T).IsSubclassOf(typeof(BaseClass)))
{
throw new Exception("Manager: Should not be here: The generic type should derive from BaseClass");
}
}
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在编译时这样做?谢谢.