我有一个 List<Users>
- Users 有一个 Username 属性。
我想知道的是 - 是否有更好的方法来获取所有用户名的 List<string>
,而不仅仅是通过循环并构建我的新列表?
我有一个 List<Users>
- Users 有一个 Username 属性。
我想知道的是 - 是否有更好的方法来获取所有用户名的 List<string>
,而不仅仅是通过循环并构建我的新列表?
使用 LINQ:
List<string> usernames = users.Select(u => u.UserName).ToList();
像这样:
List<string> userNames = users.ConvertAll(u => u.UserName);
请注意,userNames
列表不会反映对 users
或其 UserName
的后续更改。
public class ConvertingList<TSrc, TDest> : IList<TDest>
{
private readonly IList<TSrc> _inner;
private readonly Func<TSrc, TDest> _conv;
public ConvertingList(IList<TSrc> inner, Func<TSrc, TDest> conv)
{
_inner = inner;
_conv = conv;
}
public TDest this[int index]
{
get
{
return ReferenceEquals(null, _inner[index]) ? default(TDest) : _conv(_inner[index]);
}
set
{
throw new NotSupportedException("Readonly collection");
}
}
public int Count
{
get
{
return _inner.Count;
}
}
public bool IsReadOnly
{
get
{
return true;
}
}
public int IndexOf(TDest item)
{
if(ReferenceEquals(item, null))
{
for(int i = 0; i != Count; ++i)
if(ReferenceEquals(this[i], null))
return i;
}
else
{
for(int i = 0; i != Count; ++i)
if(item.Equals(this[i]))
return i;
}
return -1;
}
public void Insert(int index, TDest item)
{
throw new NotSupportedException("Readonly collection");
}
public void RemoveAt(int index)
{
throw new NotSupportedException("Readonly collection");
}
public void Add(TDest item)
{
throw new NotSupportedException("Readonly collection");
}
public void Clear()
{
throw new NotSupportedException("Readonly collection");
}
public bool Contains(TDest item)
{
return IndexOf(item) != -1;
}
public void CopyTo(TDest[] array, int arrayIndex)
{
if(array == null)
throw new ArgumentNullException();
if(arrayIndex < 0)
throw new ArgumentOutOfRangeException();
if(array.Rank != 1 || array.Length < arrayIndex + Count)
throw new ArgumentException();
foreach(TDest item in this)
array[arrayIndex++] = item;
}
public bool Remove(TDest item)
{
throw new NotSupportedException("Readonly collection");
}
public IEnumerator<TDest> GetEnumerator()
{
foreach(TSrc srcItem in _inner)
yield return ReferenceEquals(null,srcItem) ? default(TDest) : _conv(srcItem)
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
有了这个,那么:
IList<string> userNames = new ConvertingList<User, string>(users, u => u.Username);
将在常数时间内创建一个新对象,该对象表现为名称的只读列表。
(对空用户进行保护,在这里返回空字符串,当然也可以提供其他行为)。
ConvertAll
更好或更差取决于使用情况,这正是我给出两个选项作为我的答案的原因。如果您需要获取大小,然后访问几个索引,它会更好。如果您需要循环两次,那么它就更糟了。如果您需要进行更改,则完全无用。说“一定要”使用ConvertAll
而不是Select
是微观优化,一旦您习惯以这种方式进行操作并且没有任何副作用,这种优化就变得免费了。 - Jon Hannavar usernames = users.Select(u => u.Username).ToList();
你做
List<string> userNames = users.ConvertAll(u => u.UserName);