如何将Linq应用于可观察的通用财产集合?

时间:2019-03-19 07:09:24

标签: c# .net

如何将linq概念应用于通用属性集合。我已经将数据表转换为集合,就像Converter

我有DataTable,然后将其转换为Collection

class Program
{
static void Main(string[] args)
{
    DataTable dtResult = new DataTable();
    dtResult.Columns.Add("ID", typeof(int));
    dtResult.Columns.Add("Name", typeof(string));
    DataRow dtRow = dtResult.NewRow();
    dtRow["ID"] = 1;
    dtRow["Name"] = "Bala";
    dtResult.Rows.Add(dtRow);
    dtRow = dtResult.NewRow();
    dtRow["ID"] = 2;
    dtRow["Name"] = "Bala1";
    dtResult.Rows.Add(dtRow);
    var Collection = Convert(dtResult);

    //  var property = Collection.Where(a=>a.Properties.Where(x => (x as GenericProperty).Name.Equals("ID") && (x as GenericProperty).Value.Equals(1));
    // I would like to get the ID matching 2 Record How to get this using linq query
}

private static ObservableCollection<GenericObject> Convert(DataTable toConvert)
{
    ObservableCollection<GenericObject> _result = new ObservableCollection<GenericObject>();

    foreach (DataRow _row in toConvert.Rows)
    {
        GenericObject _genericObject = new GenericObject();
        foreach (DataColumn _column in toConvert.Columns)
        {
            _genericObject.Properties.Add(new GenericProperty(_column.ColumnName, _row[_column]));
        }
        _result.Add(_genericObject);
    }

    return _result;
}
}
public class GenericObject
{

private readonly ObservableCollection<GenericProperty> properties = new ObservableCollection<GenericProperty>();

public GenericObject(params GenericProperty[] properties)
{
    foreach (var property in properties)
        Properties.Add(property);
}

public ObservableCollection<GenericProperty> Properties
{
    get { return properties; }
}

}
public class GenericProperty : INotifyPropertyChanged
{
public GenericProperty(string name, object value)
{
    Name = name;
    Value = value;
}

public string Name { get; private set; }
public object Value { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
}

现在我的问题是我如何应用linq概念来获取匹配记录?

1 个答案:

答案 0 :(得分:1)

这是您想要的吗?

var property =
    from a in Collection
    where a.Properties.Any(p => p.Name == "ID" && (int)p.Value == 1)
    select a;

给出:

property