[英]How to get all properties of a class where the property is based on a certain type
[英]Grouping and ordering class object based on there certain properties?
我有一个具有Description
属性的product
类,并具有3 product
对象:
Product product1 = new Product("This is bottom product");
Product product2 = new Product("This is top product");
Product product3 = new Product("This is medium product");
List<Product> lst = new List<Product>();
lst.Add(product1);
lst.Add(product2);
lst.Add(product3);
我想重新排列这些对象,以便所有具有top
description
的products
都位于顶部,具有bottom
description
product
位于底部。
var res = lst.Where(p => p.Desription == "This is top product")
.Concat(lst.Where(p => p.Desription == "This is medium product"))
.Concat(lst.Where(p => p.Desription == "This is bottom product")).ToList();
我已经对上述查询进行了编码以实现此目的。 这给我返回正确的结果。 但是我不确定这是否是解决此问题的最有效方法?
有人可以建议任何替代/性能更好的方法吗?
注意:我已经在这里简化了问题。 否则,产品将具有更多的对象和属性。
编辑:
比比较器(更快速)更好的解决方案:
public enum ProductType
{
Bottom=0,
Medium,
Top,
}
public class Product
{
public ProductType Type { get; set; }
//the rest of properties here
}
var list = new List<Product>();
var orderedList = list.OrderBy(x => (int)x.Type).ToList();
如果您不想在现有类中添加任何内容,则可以将其包装或扩展?
鉴于您的问题:
var res = lst.Where(p => p.Desription == "This is top product")
.Concat(lst.Where(p => p.Desription == "This is medium product"))
.Concat(lst.Where(p => p.Desription == "This is bottom product")).ToList();
我相信您正在寻找的是这样的:
var res = lst.OrderBy(p => p.Desription);
我想指出的是,您用于“说明”的变量的拼写错误。
使用辅助Dictionary
:
Dictionary<string, int> myDic = new Dictionary<string, int>
{
{"top", 1},
{"medium", 2},
{"bottom", 3}
};
var res = lst.OrderBy(c => myDic[c.Desription.Split(' ')[2]]);
如果您知道每个描述将仅包含特定的单词“顶部”,“底部”,“中等”,并且仅包含以下其中之一 ,请尝试以下操作:
List<Product> res = new List<Product>();
for (int i = 0; i < lst.Count(); i++)
{
res.AddRange(lst.Where(p => p.Desription.Contains("top").ToList());
res.AddRange(lst.Where(p => p.Desription.Contains("medium").ToList());
res.AddRange(lst.Where(p => p.Desription.Contains("bottom").ToList());
}
我使用AddRange
而不是Add
因为可能有多个“顶部”,“中等”或“底部”产品。
如果描述在同一句子中包含“ top”和“ bottom”,“ top”和“ medium”等,也将不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.